c# - 泛型和 "One of the parameters of a binary operator must be the containing type"错误

标签 c# operators operator-overloading

声明二元运算符时,至少一种操作数类型必须是包含类型。总的来说,这听起来是一个不错的设计决策。但是没想到下面的代码会导致这个错误:

public class Exp<T>
{
    public static Exp<int> operator +(Exp<int> first, Exp<int> second)
    {
        return null;
    }
}

这个运算符有什么问题?为什么这种情况属于c#的运算符重载限制?允许这种声明是否危险?

最佳答案

因为包含类型是Exp<T> , 不是 Exp<int> .您在这里尝试做的是 a la C++ 特化,这在 C# 中是不可能的。

关于c# - 泛型和 "One of the parameters of a binary operator must be the containing type"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6891776/

相关文章:

C#动态事件订阅

c# - 在 C# api Controller 中获取请求来源

c++ - C++ 类中的运算符

Java 关系运算符

c++ - 如何为模板 'using' 类型别名的流输出运算符 << 提供重载?

c++ - 前缀运算符重载

c# - 在 C# 中,是否有一种干净的方法来检查多级空引用

c# - Zed graph graphpane-改变轴的颜色

php - 3个不同的等于

c++ - 重载虚拟方法与非虚拟方法有何不同?