zoukankan      html  css  js  c++  java
  • 动态类型转化

    最近在做项目的时候,因为懒得一个一个字段地赋值,使用了反射动态为属性赋值,但是碰到类型转换时错误,

    public
     static object TypeRransition(Type t, object value)         {             object result = null;             switch (t.Name)             {                 case "String":                     result = Convert.ToString(value);                     break;                 case "Int32":                     result = Convert.ToInt32(value);                     break;                 case "DateTime":                     result = Convert.ToDateTime(value);                     break;                 case "Double":                     result = Convert.ToDouble(value);                     break;                 case "Decimal":                     result = Convert.ToDecimal(value);                     break;                 case "Byte":                     result = Convert.ToByte(value);                     break;                 case "Boolean":                     result = Convert.ToBoolean(value);                     break;                 case "Guid":                     result = new Guid();                     break;             }             return result;         }


    后来发现代码还可以精简
    public static object TypeRransition(Type type, object value)
            {
                object obj = null;
                if (!Convert.IsDBNull(value))
                {
                    if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
                    {
                        Type t = type.GetGenericArguments()[0];
                        string a = t.Name;
                        obj = TypeRransition(t, value);
                    }
                    else
                    {
                        obj = Convert.ChangeType(value, type);
                    }
                }
                return obj;
            }
  • 相关阅读:
    《MySQL入门很简单》练习7.4
    《MySQL入门很简单》练习6.9
    《MySQL入门很简单》练习6.6
    《MySQL入门很简单》练习6.5
    "mysql"不是内部或外部命令,也不是可运行的程序或批处理文件
    TControl与Windows消息
    TObject与消息分发
    长串
    使用TSplitter控件调整其他控件大小简便方法
    Cocos2d-x缓存机制(一)
  • 原文地址:https://www.cnblogs.com/Lance-Lan/p/3186510.html
Copyright © 2011-2022 走看看