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; }
  • 相关阅读:
    Apache Solr入门教程(初学者之旅)
    Codeforces 631 (Div. 2) E. Drazil Likes Heap 贪心
    Codeforces 631 (Div. 2) D. Dreamoon Likes Sequences 位运算^ 组合数 递推
    Codeforces 631 (Div. 2) C. Dreamoon Likes Coloring 思维or构造
    python中的类型转换
    MVC3.0在各个版本IIS中的部署
    get和post的区别
    Vue和React对比
    谈谈你对web标注和W3c的理解和认识
    js中的undefined 和null
  • 原文地址:https://www.cnblogs.com/CielWater/p/4930484.html
Copyright © 2011-2022 走看看