好的,你可以这样做:
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))
{
var strongConverter = (Func<string, T>) converter;
return strongConverter(value);
}
}