我会选择TypeConverter 的东西。它基本上是一个转换价值观和文化的课程。 TypeConverter 和Convert.ChangeType 的主要区别在于后者需要源类型上的 IConvertible 接口,而 TypeConverters 可以处理任何对象。
我为此创建了一个辅助类,因为我经常将不同的配置对象存储在 xml 文件中。这也是为什么在 CultureInfo.InvariantCulture 之间进行硬编码转换的原因。
public static class TypeConversion {
public static Object Convert(Object source, Type targetType) {
var sourceType = source.GetType();
if (targetType.IsAssignableFrom(sourceType))
return source;
var sourceConverter = TypeDescriptor.GetConverter(source);
if (sourceConverter.CanConvertTo(targetType))
return sourceConverter.ConvertTo(null, CultureInfo.InvariantCulture, source, targetType);
var targetConverter = TypeDescriptor.GetConverter(targetType);
if (targetConverter.CanConvertFrom(sourceType))
return targetConverter.ConvertFrom(null, CultureInfo.InvariantCulture, source);
throw new ArgumentException("Neither the source nor the target has a TypeConverter that supports the requested conversion.");
}
public static TTarget Convert<TTarget>(object source) {
return (TTarget)Convert(source, typeof(TTarget));
}
}
完全可以创建自己的 TypeConverter 来处理系统类型,例如 System.Version(它不实现 IConvertible),以支持从包含版本号(“a.b.c.d”)的字符串到实际版本对象的转换。
public class VersionTypeConverter : TypeConverter {
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) {
if (sourceType == typeof(string))
return true;
return base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) {
var s = value as string;
if (s != null)
return new Version(s);
return base.ConvertFrom(context, culture, value);
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) {
if (destinationType == typeof(string))
return true;
return base.CanConvertTo(context, destinationType);
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) {
var v = value as Version;
if (v != null && destinationType == typeof(string)) {
return v.ToString();
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
要实际使用此提供程序,您需要在应用程序启动期间注册它,使用TypeDescriptor.AddProvider,传入自定义TypeDescriptionProvider 和typeof(Version)。这需要在TypeDescriptorProvider.GetTypeDescriptor方法中返回一个自定义的CustomTypeDescriptor,并且描述符需要重写GetConverter返回一个新的VersionTypeConverter实例。简单的。 ;)