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

时间:2023-09-06 14:33:02
        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()[];
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);
}