11

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

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
}

我可以看到编译器可能会抱怨这个(“无法将类型 'String' 转换为 'T'”),即使代码不应该在运行时导致任何逻辑错误。有什么方法可以实现我想要的吗?铸造没有帮助...

4

1 回答 1

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

    ...
}

这将涉及值类型的装箱,但它会起作用。

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

或者,您可能想要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
}
于 2011-02-21T12:06:38.810 回答