码迷,mamicode.com
首页 > Windows程序 > 详细

一个好用的C#类型转换器

时间:2015-12-30 21:58:24      阅读:427      评论:0      收藏:0      [点我收藏+]

标签:

        public static object ChangeType(object value, Type targetType)
        {
            
            if (targetType.IsGenericType && targetType.GetGenericTypeDefinition() == typeof (Nullable<>))
            {
                NullableConverter nullableConverter = new NullableConverter(targetType);
                Type convertType = nullableConverter.UnderlyingType;
                return Convert.ChangeType(value, convertType);
            }
            if (value == null && targetType.IsGenericType)
            {
                return Activator.CreateInstance(targetType);
            }
            if (value == null)
            {
                return null;
            }
            if (targetType == value.GetType())
            {
                return value;
            }
            if (targetType.IsEnum)
            {
                if (value is string)
                {
                    return Enum.Parse(targetType, value as string);
                }
                else
                {
                    return Enum.ToObject(targetType, value);
                }   
            }
            if (!targetType.IsInterface && targetType.IsGenericType)
            {
                Type innerType = targetType.GetGenericArguments()[0];
                object innerValue = ChangeType(value, innerType);
                return Activator.CreateInstance(targetType, new object[] { innerValue });
            }
            if (value is string && targetType == typeof (Guid))
            {
                return new Guid(value as string);
            }
            if (value is string && targetType == typeof (Version))
            {
                return new Version(value as string);
            }
            if (!(value is IConvertible))
            {
                return value;
            }
            return Convert.ChangeType(value, targetType);
        }

 

一个好用的C#类型转换器

标签:

原文地址:http://www.cnblogs.com/fengxiaoling/p/5089899.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!