예제 #1
0
 /// <summary>
 /// 转换为为强类型
 /// </summary>
 /// <param name="type"></param>
 /// <param name="value"></param>
 /// <returns></returns>
 internal static object ConvertObject(Type type, object value)
 {
     if (value == null)
     {
         return(value);
     }
     if (type == value.GetType())
     {
         return(value);
     }
     if (convertMethod.Count == 0)
     {
         convertMethod.TryAdd(typeof(byte[]), (a) =>
         {
             return((byte[])a);
         });
         convertMethod.TryAdd(typeof(Guid), (a) =>
         {
             return(new Guid(a.ToString()));
         });
         //convertMethod.Add(typeof(Enum), (a) =>
         //{
         //    return Convert.ToInt32(a);
         //});
     }
     if (type.IsEnum)
     {
         type = type.GetEnumUnderlyingType();
     }
     if (convertMethod.ContainsKey(type))
     {
         return(convertMethod[type](value));
     }
     if (Nullable.GetUnderlyingType(type) != null)
     {
         //Nullable<T> 可空属性
         type = type.GenericTypeArguments[0];
     }
     try
     {
         return(Convert.ChangeType(value, type));
     }
     catch
     {
         return(null);
     }
 }
예제 #2
0
 /// <summary>
 /// 转化值,并处理默认值
 /// </summary>
 /// <param name="value"></param>
 /// <param name="type"></param>
 /// <returns></returns>
 public static object CheckNullValue(object value, Type type = null)
 {
     if (type == null && value == null)
     {
         return(DBNull.Value);
         //throw new CRLException("至少一项不能为空");
     }
     if (value != null)
     {
         type = value.GetType();
     }
     if (nullCheckMethod.Count == 0)
     {
         nullCheckMethod.TryAdd(typeof(bool), (a) =>
         {
             return(Convert.ToInt32(a));
         });
         nullCheckMethod.TryAdd(typeof(string), (a) =>
         {
             return(a + "");
         });
         nullCheckMethod.TryAdd(typeof(Enum), (a) =>
         {
             return(Convert.ToInt32(a));
         });
         nullCheckMethod.TryAdd(typeof(DateTime), (a) =>
         {
             DateTime time = (DateTime)a;
             if (time.Year == 1)
             {
                 a = DateTime.Now;
             }
             return(a);
         });
         nullCheckMethod.TryAdd(typeof(byte[]), (a) =>
         {
             if (a == null)
             {
                 return(0);
             }
             return(a);
         });
         nullCheckMethod.TryAdd(typeof(Guid), (a) =>
         {
             if (a == null)
             {
                 return(Guid.NewGuid().ToString());
             }
             return(a);
         });
     }
     if (nullCheckMethod.ContainsKey(type))
     {
         return(nullCheckMethod[type](value));
     }
     if (type.BaseType == typeof(Enum))
     {
         return(nullCheckMethod[type.BaseType](value));
     }
     if (value == null)
     {
         return(DBNull.Value);
     }
     return(value);
 }