再不用担心DataRow类型转换和空值了(使用扩展方…

2018-06-17 19:19:41来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

在使用DataRow读取数据时,通常会遇到数据可能为Null, 但是又需要转换为如int等其它类型的数据,因此就通常会写这样的代码:

if (dr[name] != DBNull.Value && dr[name] != null)
{
    if (!int.TryParse(dr[name].ToString(), out result))
        throw new Exception("整形转换失败");
}

而且这样的代码通常会大段大段出现在很多地方。
对于比较懒惰的程序员来说,这样的RY(repeat yourself)是一件很痛苦的事情,因此是时候来想个更好的方法了。这里首先想到的就是Extension Method。

很简单的几句代码,有了这个方法之后,在使用DataRow时,就可以通过扩展方法读取数据了

model.Id =  dr.SafeRead<Int32>("Id",0);
model.codeNum = dr.GetString("codeNum");


简单但是实用的代码,希望对大家在项目中有所帮助。

这里参考了,一下两篇文章,并进行了代码重新组织,最后是整理后类源码

使用 Extension Methods 来使 IDataReader 更加方便

C#底层SqlDataReader类常用扩展

    public static class SystemDataExtension
    {
        #region DataReader 扩展
        public static T SafeRead<T>(this IDataReader reader, string fieldName, T defaultValue)
        {
            try
            {
                object obj = reader[fieldName];
                if (obj == null || obj == System.DBNull.Value)
                    return defaultValue;

                return (T)Convert.ChangeType(obj, defaultValue.GetType());
            }
            catch
            {
                return defaultValue;
            }
        }

        /// <summary>          
        /// 获取字符串类型数据   
        /// </summary>     
        /// <param name="dr"></param>  
        /// <param name="name"></param>      
        /// <returns></returns>      
        public static string GetString(this IDataReader dr, string name)
        {

            if (dr[name] != DBNull.Value && dr[name] != null)
                return dr[name].ToString();
            return String.Empty;
        }
        /// <summary>          
        /// 获取非空类型数据         
        /// </summary>          
        /// <param name="con"></param>
        /// <param name="name"></param>
        /// <returns></returns>        
        public static DateTime GetDateTime(this IDataReader dr, string name)
        {
            DateTime result = DateTime.Now;
            if (dr[name] != DBNull.Value && dr[name] != null)
            {
                if (!DateTime.TryParse(dr[name].ToString(), out result))
                    throw new Exception("日期格式数据转换失败");
            }
            return result;
        }
        /// <summary>          
        /// 获取可空类型日期数据         
        /// </summary>          
        /// <param name="dr"></param>         
        /// <param name="name"></param>         
        /// <returns></returns>          
        public static DateTime? GetNullDateTime(this IDataReader dr, string name)
        {

            DateTime? result = null;
            DateTime time = DateTime.Now;
            if (dr[name] != DBNull.Value && dr[name] != null)
            {
                if (!DateTime.TryParse(dr[name].ToString(), out time))
                    throw new Exception("日期格式数据转换失败");
                result = time;
            }
            return result;
        }

        /// <summary>          
        /// 获取guid类型数据         
        /// </summary>          
        /// <param name="dr"></param>         
        /// <param name="name"></param>         
        /// <returns></returns>          
        public static Guid GetGuid(this IDataReader dr, string name)
        {
            Guid guid = Guid.Empty;
            if (dr[name] != DBNull.Value && dr[name] != null)
            {
                if (Guid.TryParse(dr[name].ToString(), out guid))
                    throw new Exception("guid类型数据转换失败");
            }
            return guid;
        }
        /// <summary>         
        /// 获取整形数据         
        /// </summary>          
        /// <param name="dr"></param>         
        /// <param name="name"></param>         
        /// <returns></returns>         
        public static int GetInt32(this IDataReader dr, string name)
        {
            int result = 0;

            if (dr[name] != DBNull.Value && dr[name] != null)
            {
                if (!int.TryParse(dr[name].ToString(), out result))
                    throw new Exception("整形转换失败");
            }
            return result;
        }

        /// <summary>         
        /// 获取双精度类型数据 
        /// </summary>    
        /// <param name="dr"></param>   
        /// <param name="name"></param>     
        /// <returns></returns>          
        public static double GetDouble(this IDataReader dr, string name)
        {
            double result = 0.00;
            if (dr[name] != DBNull.Value && dr[name] != null)
            {
                if (!double.TryParse(dr[name].ToString(), out result))
                    throw new Exception("双精度类型转换失败");
            }
            return result;
        }
        /// <summary>          
        /// 获取单精度类型数据         
        /// </summary>          
        /// <param name="dr"></param>         
        /// <param name="name"></param>         
        /// <returns></returns>          
        public static float GetSingle(this IDataReader dr, string name)
        {
            float result = 0.00f;
            if (dr[name] != DBNull.Value && dr[name] != null)
            {
                if (!float.TryParse(dr[name].ToString(), out result))
                    throw new Exception("单精度类型转换失败");
            }

            return result;
        }

        /// <summary>          
        /// 获取decimal类型数据         
        /// </summary>          
        /// <param name="dr"></param>  
        /// <param name="name"></param>     
        /// <returns></returns>          
        public static decimal GetDecimal(this IDataReader dr, string name)
        {
            decimal result = 0.00m;
            if (dr[name] != DBNull.Value && dr[name] != null)
            {
                if (!decimal.TryParse(dr[name].ToString(), out result))
                    throw new Exception("Decimal类型转换失败");
            }
            return result;
        }

        /// <summary>          
        /// 获取int16类型数据         
        /// </summary>          
        /// <param name="dr"></param>         
        /// <param name="name"></param>         
        /// <returns></returns>          
        public static Int16 GetInt16(this IDataReader dr, string name)
        {
            short result = 0;
            if (dr[name] != DBNull.Value && dr[name] != null)
            {
                if (!short.TryParse(dr[name].ToString(), out result))
                    throw new Exception("短整形转换失败");
            }
            return result;
        }

        /// <summary>          
        /// 获取Byte类型数据         
        /// </summary> 
        ///  <param name="dr"></param>         
        /// <param name="name"></param>         
        /// <returns></returns>          
        public static byte GetByte(this IDataReader dr, string name)
        {
            byte result = 0;
            if (dr[name] != DBNull.Value && dr[name] != null)
            {
                if (!byte.TryParse(dr[name].ToString(), out result))
                    throw new Exception("Byte类型转换失败");
            }
            return result;
        }

        /// <summary>          
        /// 获取bool类型数据如果传值是1或者是返回true;        
        /// </summary>          
        /// <param name="con"></param>         
        /// <param name="name"></param>         
        /// <returns></returns>          
        public static bool GetBool(this IDataReader dr, string name)
        {
            if (dr[name] != DBNull.Value && dr[name] != null)
            {
                return dr[name].ToString() == "1" || dr[name].ToString() == "是" || dr[name].ToString().ToLower() == "true";
            }
            return false;
        } 
        #endregion

        #region DataRow 扩展
        public static T SafeRead<T>(this DataRow dr, string fieldName, T defaultValue)
        {
            try
            {
                object obj = dr[fieldName];
                if (obj == null || obj == System.DBNull.Value)
                    return defaultValue;

                return (T)Convert.ChangeType(obj, defaultValue.GetType());
            }
            catch
            {
                return defaultValue;
            }
        }

        /// <summary>          
        /// 获取字符串类型数据   
        /// </summary>     
        /// <param name="dr"></param>  
        /// <param name="name"></param>      
        /// <returns></returns>      
        public static string GetString(this DataRow dr, string name)
        {

            if (dr[name] != DBNull.Value && dr[name] != null)
                return dr[name].ToString();
            return String.Empty;
        }
        /// <summary>          
        /// 获取非空类型数据         
        /// </summary>          
        /// <param name="con"></param>
        /// <param name="name"></param>
        /// <returns></returns>        
        public static DateTime GetDateTime(this DataRow dr, string name)
        {
            DateTime result = DateTime.Now;
            if (dr[name] != DBNull.Value && dr[name] != null)
            {
                if (!DateTime.TryParse(dr[name].ToString(), out result))
                    throw new Exception("日期格式数据转换失败");
            }
            return result;
        }
        /// <summary>          
        /// 获取可空类型日期数据         
        /// </summary>          
        /// <param name="dr"></param>         
        /// <param name="name"></param>         
        /// <returns></returns>          
        public static DateTime? GetNullDateTime(this DataRow dr, string name)
        {

            DateTime? result = null;
            DateTime time = DateTime.Now;
            if (dr[name] != DBNull.Value && dr[name] != null)
            {
                if (!DateTime.TryParse(dr[name].ToString(), out time))
                    throw new Exception("日期格式数据转换失败");
                result = time;
            }
            return result;
        }

        /// <summary>          
        /// 获取guid类型数据         
        /// </summary>          
        /// <param name="dr"></param>         
        /// <param name="name"></param>         
        /// <returns></returns>          
        public static Guid GetGuid(this DataRow dr, string name)
        {
            Guid guid = Guid.Empty;
            if (dr[name] != DBNull.Value && dr[name] != null)
            {
                if (Guid.TryParse(dr[name].ToString(), out guid))
                    throw new Exception("guid类型数据转换失败");
            }
            return guid;
        }
        /// <summary>         
        /// 获取整形数据         
        /// </summary>          
        /// <param name="dr"></param>         
        /// <param name="name"></param>         
        /// <returns></returns>         
        public static int GetInt32(this DataRow dr, string name)
        {
            int result = 0;

            if (dr[name] != DBNull.Value && dr[name] != null)
            {
                if (!int.TryParse(dr[name].ToString(), out result))
                    throw new Exception("整形转换失败");
            }
            return result;
        }

        /// <summary>         
        /// 获取双精度类型数据 
        /// </summary>    
        /// <param name="dr"></param>   
        /// <param name="name"></param>     
        /// <returns></returns>          
        public static double GetDouble(this DataRow dr, string name)
        {
            double result = 0.00;
            if (dr[name] != DBNull.Value && dr[name] != null)
            {
                if (!double.TryParse(dr[name].ToString(), out result))
                    throw new Exception("双精度类型转换失败");
            }
            return result;
        }
        /// <summary>          
        /// 获取单精度类型数据         
        /// </summary>          
        /// <param name="dr"></param>         
        /// <param name="name"></param>         
        /// <returns></returns>          
        public static float GetSingle(this DataRow dr, string name)
        {
            float result = 0.00f;
            if (dr[name] != DBNull.Value && dr[name] != null)
            {
                if (!float.TryParse(dr[name].ToString(), out result))
                    throw new Exception("单精度类型转换失败");
            }

            return result;
        }

        /// <summary>          
        /// 获取decimal类型数据         
        /// </summary>          
        /// <param name="dr"></param>  
        /// <param name="name"></param>     
        /// <returns></returns>          
        public static decimal GetDecimal(this DataRow dr, string name)
        {
            decimal result = 0.00m;
            if (dr[name] != DBNull.Value && dr[name] != null)
            {
                if (!decimal.TryParse(dr[name].ToString(), out result))
                    throw new Exception("Decimal类型转换失败");
            }
            return result;
        }

        /// <summary>          
        /// 获取int16类型数据         
        /// </summary>          
        /// <param name="dr"></param>         
        /// <param name="name"></param>         
        /// <returns></returns>          
        public static Int16 GetInt16(this DataRow dr, string name)
        {
            short result = 0;
            if (dr[name] != DBNull.Value && dr[name] != null)
            {
                if (!short.TryParse(dr[name].ToString(), out result))
                    throw new Exception("短整形转换失败");
            }
            return result;
        }

        /// <summary>          
        /// 获取Byte类型数据         
        /// </summary> 
        ///  <param name="dr"></param>         
        /// <param name="name"></param>         
        /// <returns></returns>          
        public static byte GetByte(this DataRow dr, string name)
        {
            byte result = 0;
            if (dr[name] != DBNull.Value && dr[name] != null)
            {
                if (!byte.TryParse(dr[name].ToString(), out result))
                    throw new Exception("Byte类型转换失败");
            }
            return result;
        }

        /// <summary>          
        /// 获取bool类型数据如果传值是1或者是返回true;        
        /// </summary>          
        /// <param name="con"></param>         
        /// <param name="name"></param>         
        /// <returns></returns>          
        public static bool GetBool(this DataRow dr, string name)
        {
            if (dr[name] != DBNull.Value && dr[name] != null)
            {
                return dr[name].ToString() == "1" || dr[name].ToString() == "是" || dr[name].ToString().ToLower() == "true";
            }
            return false;
        }
        #endregion
    }

  

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:窗体间传值(委托)

下一篇:Linq表达式、Lambda表达式你更喜欢哪个?