C#通用类型转换 Convert.ChangeType - 小众知识

C#通用类型转换 Convert.ChangeType

2021-12-01 06:53:06 苏内容
  标签: 类型
阅读:3700

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

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);

}

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

 

Example:

 

 

重载列表
 
 名称说明
 ChangeType(Object, Type)返回一个指定类型的对象,该对象的值等效于指定的对象。
 ChangeType(Object, TypeCode)返回指定类型的对象,其值等效于指定对象。
 ChangeType(Object, Type, IFormatProvider)返回指定类型的对象,其值等效于指定对象。 参数提供区域性特定的格式设置信息。
 ChangeType(Object, TypeCode, IFormatProvider)返回指定类型的对象,其值等效于指定对象。 参数提供区域性特定的格式设置信息。


扩展阅读
相关阅读
© CopyRight 2010-2021, PREDREAM.ORG, Inc.All Rights Reserved. 京ICP备13045924号-1