获取DataRow某列的值的封装

public class DataHelper
    {

        const string DEFSTR = "";
        /// <summary>
        /// 根据一个类型,获取其默认值,数字默认是为0,字符串默认值为一个空字符串
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        static T GetDefault<T>()
        {
            T t = default(T);
            //如果是字符串类型,则返回一个空字符串
            if (DEFSTR is T)
            {
                return (T)((object)DEFSTR);
            }
            return t;
        }

        /// <summary>
        /// 获取一个DataRow某列的值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dr"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public static T GetValue<T>(DataRow dr, string name)
        {
            try
            {
                if (dr[name] == DBNull.Value)
                {
                    return GetDefault<T>();
                }
                else
                {
                    return (T)dr[name];
                }
            }//如果不存在这一列
            catch (ArgumentException ex)
            {
                return GetDefault<T>();
            }
        }
    }
posted @ 2011-04-12 10:14  再快一点  阅读(4617)  评论(0编辑  收藏  举报