其他分享
首页 > 其他分享> > 类型自行判定转化函数

类型自行判定转化函数

作者:互联网

原文链接:http://www.cnblogs.com/CielWater/p/4930484.html
     /// <summary>
        /// 转换类型
/// </summary> /// <param name="type"></param> /// <param name="value"></param> /// <returns></returns> public static object ConvertValue(Type type, object value) { if (Convert.IsDBNull(value) || (value == null)) { return null; } if (type.IsValueType && !type.IsEnum && !type.IsPrimitive && !type.IsSerializable) { string data = value.ToString(); return SerializationManager.Deserialize(type, data); } Type type2 = value.GetType(); if (type == type2) { return value; } if (((type == typeof(Guid)) || (type == typeof(Guid?))) && (type2 == typeof(string))) { if (string.IsNullOrEmpty(value.ToString())) { return null; } return new Guid(value.ToString()); } if (((type == typeof(DateTime)) || (type == typeof(DateTime?))) && (type2 == typeof(string))) { if (string.IsNullOrEmpty(value.ToString())) { return null; } return Convert.ToDateTime(value); } if (type.IsEnum) { try { return Enum.Parse(type, value.ToString(), true); } catch { return Enum.ToObject(type, value); } } if (((type == typeof(bool)) || (type == typeof(bool?)))) { bool tempbool = false; if (bool.TryParse(value.ToString(), out tempbool)) { return tempbool; } else { //处理 Request.Form 的 checkbox 如果没有返回值就是没有选中false if (string.IsNullOrEmpty(value.ToString())) return false; else { if (value.ToString() == "0") { return false; } return true; } } } if (type.IsGenericType) { type = type.GetGenericArguments()[0]; } return Convert.ChangeType(value, type); } /// <summary> /// 转换数据类型 /// </summary> /// <typeparam name="TResult"></typeparam> /// <param name="value"></param> /// <returns></returns> public static TResult ConvertValue<TResult>(object value) { if (Convert.IsDBNull(value) || value == null) return default(TResult); object obj = ConvertValue(typeof(TResult), value); if (obj == null) { return default(TResult); } return (TResult)obj; }

 

转载于:https://www.cnblogs.com/CielWater/p/4930484.html

标签:return,函数,value,自行,判定,typeof,ToString,null,type
来源: https://blog.csdn.net/weixin_30871701/article/details/97130149