C#动态类型转换

Adi*_*rda 6 c#

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

Mar*_*ell 20

最实用,最通用的字符串转换方法是TypeConverter:

public static T Parse<T>(string value)
{
    // or ConvertFromInvariantString if you are doing serialization
    return (T)TypeDescriptor.GetConverter(typeof(T)).ConvertFromString(value);
}
Run Code Online (Sandbox Code Playgroud)

更多类型具有类型转换器而不是器件IConvertible等,您还可以在新的类型中添加转换器 - 在编译时;

[TypeConverter(typeof(MyCustomConverter))]
class Foo {...}

class MyCustomConverter : TypeConverter {
     // override ConvertFrom/ConvertTo 
}
Run Code Online (Sandbox Code Playgroud)

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

TypeDescriptor.AddAttributes(typeof(Bar),
    new TypeConverterAttribute(typeof(MyCustomConverter)));
Run Code Online (Sandbox Code Playgroud)


dri*_*iis 5

如前所述,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) } };
}
Run Code Online (Sandbox Code Playgroud)

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