zoukankan      html  css  js  c++  java
  • Nullable 类型的转换

    一直都是个头疼的问题,感谢maplye

    1.The PumaCode.org Blog

    public object ChangeType(object value, Type conversionType)
    {
        if ( conversionType.IsGenericType &&
            conversionType.GetGenericTypeDefinition( ).Equals( typeof( Nullable<> ) ) ) {
     
            if(value == null)
                return null;
     
            System.ComponentModel.NullableConverter nullableConverter
                = new System.ComponentModel.NullableConverter(conversionType);
     
            conversionType = nullableConverter.UnderlyingType;
        }
     
        return Convert.ChangeType(value, conversionType);
    }
     

    引用:http://blog.pumacode.org/2006/05/18/using-convert-changetype-on-nullable-types/


    2.Paul Wilson's .NET Blog

    public class DataTypeConverter
        {
            public static object ChangeType(Type type,object value)
            {
                if ((value == null) && type.IsGenericType)
                {
                    return Activator.CreateInstance(type);
                }
                if (value == null)
                {
                    return null;
                }
                if (type == value.GetType())
                {
                    return value;
                }
                if (type.IsEnum)
                {
                    if (value is string)
                    {
                        return Enum.Parse(type, value as string);
                    }
                    return Enum.ToObject(type, value);
                }
                if (!type.IsInterface && type.IsGenericType)
                {
                    Type type1 = type.GetGenericArguments()[0];
                    object obj1 = DataTypeConverter.ChangeType(type1,value);
                    return Activator.CreateInstance(type, new object[] { obj1 });
                }
                if ((value is string) && (type == typeof(Guid)))
                {
                    return new Guid(value as string);
                }
                if ((value is string) && (type == typeof(Version)))
                {
                    return new Version(value as string);
                }
                if (!(value is IConvertible))
                {
                    return value;
                }
                return Convert.ChangeType(value, type);
            }
        }
    引用:http://weblogs.asp.net/pjohnson/archive/2006/02/07/437631.aspx
    作者:KKcat
        
    个人博客:http://jinzhao.me/
        
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
  • 相关阅读:
    Thomas Hobbes: Leviathan
    10 Easy Steps to a Complete Understanding of SQL
    day3心得
    py编码终极版
    day2 作业
    Python 中的比较:is 与 ==
    day2-心得
    day1--心得
    day1作业
    python--open用法
  • 原文地址:https://www.cnblogs.com/jinzhao/p/1595076.html
Copyright © 2011-2022 走看看