[英]C# dynamic type conversions
我们有2个对象A和B:A是system.string,B是.net原始类型(string,int等)。 我们想编写通用代码来将B的转换(解析)值分配给A.任何建议? 谢谢,阿迪巴尔达
使用TypeConverter
进行字符串转换的最务实和最通用的方法是:
public static T Parse<T>(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<double>("5.6"));
Console.WriteLine(SimpleConvert.To<decimal>("42"));
}
}
public static class SimpleConvert
{
public static T To<T>(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<Type, Func<string, object>> dicConversions = new Dictionary <Type, Func<string, object>> {
{ typeof (Decimal), v => Convert.ToDecimal(v) },
{ typeof (double), v => Convert.ToDouble( v) } };
}
显然,您可能希望在自定义转换例程中做一些更有趣的事情,但它证明了这一点。
现有的System.Convert类和IConvertible接口出了什么问题?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.