好吧,你可以这样做:
public static T Foo<T>(string value)
{
if (typeof(T) == typeof(String))
return (T) (object) value;
if (typeof(T) == typeof(int))
return (T) (object) Int32.Parse(value);
...
}
这将涉及值类型的装箱,但它会起作用。
您确定这最好作为单一方法完成,而不是(比如说)可以由不同转换器实现的通用接口?
或者,您可能想要Dictionary<Type, Delegate>
这样的:
Dictionary<Type, Delegate> converters = new Dictionary<Type, Delegate>
{
{ typeof(string), new Func<string, string>(x => x) }
{ typeof(int), new Func<string, int>(x => int.Parse(x)) },
}
那么你会像这样使用它:
public static T Foo<T>(string value)
{
Delegate converter;
if (converters.TryGetValue(typeof(T), out converter))
{
// We know the delegate will really be of the right type
var strongConverter = (Func<string, T>) converter;
return strongConverter(value);
}
// Oops... no such converter. Throw exception or whatever
}