C#动态类型转换

我们有2个对象A和B:A是system.string,B是.net原始类型(string,int等)。 我们想编写通用代码来将B的转换(解析)值分配给A.任何建议? 谢谢,阿迪巴尔达

使用TypeConverter进行字符串转换的最实用和多function的方法是:

 public static T Parse(string value) { // or ConvertFromInvariantString if you are doing serialization return (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromString(value); } 

更多类型具有类型转换器而不是实现IConvertible等,您还可以将转换器添加到新类型 – 在编译时;

 [TypeConverter(typeof(MyCustomConverter))] class Foo {...} class MyCustomConverter : TypeConverter { // override ConvertFrom/ConvertTo } 

如果需要,也可以在运行时(对于您不拥有的类型):

 TypeDescriptor.AddAttributes(typeof(Bar), new TypeConverterAttribute(typeof(MyCustomConverter))); 

如前所述,System.Convert和IConvertible将是第一个赌注。 如果由于某种原因你不能使用它们(例如,如果内置类型的默认系统转换对你来说不够),一种方法是创建一个字典,其中包含每个转换的委托,并在其中进行查找在需要时找到正确的转换。

例如; 当您想要从String转换为X类型时,您可以拥有以下内容:

 using System; using System.Collections.Generic; class Program { static void Main(string[] args) { Console.WriteLine(SimpleConvert.To("5.6")); Console.WriteLine(SimpleConvert.To("42")); } } public static class SimpleConvert { public static T To(string value) { Type target = typeof (T); if (dicConversions.ContainsKey(target)) return (T) dicConversions[target](value); throw new NotSupportedException("The specified type is not supported"); } private static readonly Dictionary> dicConversions = new Dictionary > { { typeof (Decimal), v => Convert.ToDecimal(v) }, { typeof (double), v => Convert.ToDouble( v) } }; } 

显然,您可能希望在自定义转换例程中做一些更有趣的事情,但它certificate了这一点。

现有的System.Convert类和IConvertible接口出了什么问题?

MSDN上有类型转换的概述 ,您可以在其中获得有关该主题的更多信息。 我发现它很有用。