从Type对象获取T

时间:2018-08-21 00:05:50

标签: c# generics

我有一种方法需要T才能正常运行。我有一个Type对象作为类的属性。

public Type DefaultNumaricType {get; private set;} = typeof(double);

private T Convert<T>(string input)
{
    ...
}

我希望能够调用Convert<T>方法并获取DefaultNumaricType中指定类型的对象。

是否可能这样:

double d = Convert<DefaultNumaricType>("123.00");

1 个答案:

答案 0 :(得分:1)

您是否可能想要这样?

var converter = new Converter();

converter.Configure<double>(x => double.Parse(x));
converter.Configure<int?>(x => int.TryParse(x, out int result) ? (int?)result : null);

var value1 = converter.Convert<double>("42.123");
var value2 = converter.Convert<int?>("");

如果是这样,则是执行此操作的类:

public class Converter
{
    private Dictionary<Type, Delegate> _factories = new Dictionary<Type, Delegate>();

    public void Configure<T>(Func<string, T> factory)
    {
        _factories[typeof(T)] = factory;
    }

    public T Convert<T>(string input)
    {
        return ((Func<string, T>)_factories[typeof(T)])(input);
    }
}