返回通用方法的类型

Chr*_*ygg 11 .net generics methods return-type

我有一个泛型方法,它返回泛型类型的对象.一些代码:

public static T Foo<T>(string value)
{
    if (typeof(T) == typeof(String))
        return value;

    if (typeof(T) == typeof(int))
        return Int32.Parse(value);

    // Do more stuff
}
Run Code Online (Sandbox Code Playgroud)

我可以看到,编译器可能会抱怨这个("无法将类型'字符串’到'T’"),即使代码不会引起任何逻辑错误运行.有没有办法实现我正在寻找的东西?铸造无济于事......

Jon*_*eet 19

好吧,你可以这样做:

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);

    ...
}
Run Code Online (Sandbox Code Playgroud)

这将涉及拳击值类型,但它将工作.

您确定这最好是作为一种方法完成,而不是(比如说)可以由不同转换器实现的通用接口吗?

或者,您可能需要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)) },
}
Run Code Online (Sandbox Code Playgroud)

然后你会像这样使用它:

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
}
Run Code Online (Sandbox Code Playgroud)