【问题标题】:Return type of generic method泛型方法的返回类型
【发布时间】:2011-02-21 12:04:15
【问题描述】:

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

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'”),即使代码不应该在运行时导致任何逻辑错误。有什么方法可以实现我想要的吗?投射没有帮助......

【问题讨论】:

    标签: .net generics methods return-type


    【解决方案1】:

    嗯,你可以这样做:

    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&lt;Type, Delegate&gt;

    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
    }
    

    【讨论】:

    • 我必须做 return (T)(object)value;也适用于字符串,但这有效。谢谢! :-)
    • @Chris:字典方法对我来说感觉更干净......并且可以避免值类型的装箱。
    • @Jon:有问题的读取方法比我在这里写的要复杂一些——我只是强调了我遇到的问题。所以你的替代方法并没有真正相关,但我同意 - 这将是一种更清洁的方法。
    • @Jon:刚刚注意到您在字符串的返回语句中添加了(字符串)。这不起作用 - 它似乎必须是(对象),仅供参考。
    • 我做了一个小基准测试......我认为编译器忽略了 (T)(object) 转换(如果我调用“通用”函数或调用更多函数,时间是相同的直接调用 Int32.Parse)
    猜你喜欢
    • 2016-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-11
    • 2015-07-18
    相关资源
    最近更新 更多