简体   繁体   English

无法从Func转换 <T,T,T> 到Func <T,T,T>

[英]Cannot convert from Func<T,T,T> to Func<T,T,T>

I'm quite confused by this error: 我对这个错误很困惑:

Cannot implicitly convert type 'System.Func<T,T,T> [c:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.0\\mscorlib.dll]' to 'System.Func<T,T,T> [c:\\Program Files (x86)\\Reference Assemblies\\Microsoft\\Framework\\.NETFramework\\v4.0\\mscorlib.dll]' path\\to\\my\\project\\Operators.cs

The types are identical, why is it even trying to do a cast? 类型是相同的,为什么它甚至试图进行演员表演? Here's the code: 这是代码:

public static class Operators<T>
{
    private static Func<T,T,T> _add = null;

    public static T Add<T>(T a, T b)
    {
        if (_add == null) {
            var param1Expr = Expression.Parameter(typeof (T));
            var param2Expr = Expression.Parameter(typeof (T));
            var addExpr = Expression.Add(param1Expr, param2Expr);
            var expr = Expression.Lambda<Func<T, T, T>>(addExpr, param1Expr, param2Expr);
            _add = expr.Compile(); // <--- error occurs here
        }
        return _add.Invoke(a, b);
    }
}

The problem is that your method is generic, introducing a new type parameter T . 问题是你的方法是通用的,引入了一个新的类型参数T So the T outside the method isn't the same as the T inside the method. 所以T方法以外是不一样的T的方法内。

Just change your method to not be generic: 只需将您的方法更改为不通用:

public static T Add(T a, T b)

... and it should be fine. ......它应该没问题。

To be clearer, your code is currently equivalent to this: 为了更清楚,您的代码目前等效于此:

public static class Operators<TC>
{
    private static Func<TC, TC, TC> _add = null;

    public static TM Add<TM>(TM a, TM b)
    {
        if (_add == null) {
            var param1Expr = Expression.Parameter(typeof(TM));
            var param2Expr = Expression.Parameter(typeof(TM));
            var addExpr = Expression.Add(param1Expr, param2Expr);
            var expr = Expression.Lambda<Func<TM, TM, TM>>
                          (addExpr, param1Expr, param2Expr);
            _add = expr.Compile();
        }
        return _add.Invoke(a, b);
    }
}

Note how I've renamed the T introduced by the class to TC , and the T introduced by the method to TM . 请注意我是如何改名T全班同学介绍了TC ,而T方法来介绍TM The error message now looks more reasonable: 现在,错误消息看起来更合理:

Test.cs(19,20): error CS0029: Cannot implicitly convert type
        'System.Func<TM,TM,TM>' to 'System.Func<TC,TC,TC>'

The T for your Operators<T> class and the T type parameter for Add are different types, so there's no guarantee that the types are compatible. T你的Operators<T>类和T的类型参数Add有不同的类型,所以没有保证的类型兼容。

For example you could do: 例如,您可以这样做:

Operators<string>.Add<int>(1, 2);

The compiler emits a warning to this effect: 编译器会发出此效果的警告:

Type parameter 'T' has the same name as the type parameter from outer type 'Operators' 类型参数'T'与外部类型'Operators'中的type参数同名

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM