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