zoukankan      html  css  js  c++  java
  • 类型自行判定转化函数

         /// <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; }
  • 相关阅读:
    不知如何摧毁Kendo UI for jQuery小部件?这份指南不得不看
    MyEclipse导航代码第二弹,Java开发更便捷
    索引扫描与索引查找区别
    Chrome使用技巧
    什么是中台?所有的中台都是业务中台
    跨域资源共享CORS详解
    多线程之入门起步(三)
    聊天程序——基于Socket、Thread (二)
    多线程的相关概念(一)
    使用BCP实用工具导出导入数据
  • 原文地址:https://www.cnblogs.com/CielWater/p/4930484.html
Copyright © 2011-2022 走看看