C#通用类型转换 Convert.ChangeType

http://technet.microsoft.com/zh-cn/library/system.convert.changetype(en-us).aspx

http://www.cnblogs.com/youring2/archive/2012/07/26/2610035.html

 

Example:

static public object ChangeType(object value, Type type)
        {
            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);
                else
                    return Enum.ToObject(type, value);
            }
            if (!type.IsInterface && type.IsGenericType)
            {
                Type innerType = type.GetGenericArguments()[0];
                object innerValue = ChangeType(value, innerType);
                return Activator.CreateInstance(type, new object[] { innerValue });
            }
            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);
        } 

 

 

 名称说明
公共方法 静态成员 ChangeType(Object, Type) 返回一个指定类型的对象,该对象的值等效于指定的对象。
公共方法 静态成员 ChangeType(Object, TypeCode) 返回指定类型的对象,其值等效于指定对象。
公共方法 静态成员 ChangeType(Object, Type, IFormatProvider) 返回指定类型的对象,其值等效于指定对象。 参数提供区域性特定的格式设置信息。
公共方法 静态成员 ChangeType(Object, TypeCode, IFormatProvider) 返回指定类型的对象,其值等效于指定对象。 参数提供区域性特定的格式设置信息。
posted @ 2014-06-04 15:44  vivianC  阅读(5076)  评论(0编辑  收藏  举报