首页 > 代码库 > C#通用类型转换 Convert.ChangeType 转自网络

C#通用类型转换 Convert.ChangeType 转自网络

static public object ChangeType(object value, Type type)        {            if (value =http://www.mamicode.com/= null && type.IsGenericType) return Activator.CreateInstance(type);            if (value =http://www.mamicode.com/= 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 =http://www.mamicode.com/ 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);        }