我有一种方法需要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");
答案 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);
}
}