类型自行判定转化函数
/// <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; }