<分区>
为什么在 C# 中我们对运算符方法使用静态?
我尝试阅读互联网上的不同文章,但他们并没有帮助我回答问题。
public static int operator+(int I, Complex C)
{
return C.x + I;
}
此外,当我尝试执行 c+2 时,它工作正常,但当我执行 2+c 时,它给我一个错误,因为我没有为此调用参数匹配提供额外的重载函数。有没有什么方法可以让我用一个函数的重载运算符定义来运行两个语句,如 c+2 和 2+c?
<分区>
为什么在 C# 中我们对运算符方法使用静态?
我尝试阅读互联网上的不同文章,但他们并没有帮助我回答问题。
public static int operator+(int I, Complex C)
{
return C.x + I;
}
此外,当我尝试执行 c+2 时,它工作正常,但当我执行 2+c 时,它给我一个错误,因为我没有为此调用参数匹配提供额外的重载函数。有没有什么方法可以让我用一个函数的重载运算符定义来运行两个语句,如 c+2 和 2+c?
最佳答案
规范对用户定义的运算符有以下说明(强调我的)
The following rules apply to all operator declarations:
•An operator declaration shall include both a public and a static modifier.
•The parameter(s) of an operator shall have no modifiers.
•The signature of an operator (§15.10.2, §15.10.3, §15.10.4) shall differ from the signatures of all other operators declared in the same class.
•All types referenced in an operator declaration shall be at least as accessible as the operator itself (§8.5.5).
•It is an error for the same modifier to appear multiple times in an operator declaration.
“因为规范这么说”可能不是最令人满意的答案,但这是我所能得到的最好的答案。我猜虚拟调度对运营商来说意义不大。
关于你的第二个问题,我的方法是实现一个私有(private)静态方法来执行你的操作,然后让两个运算符实现指向它。
像这样:
public static int operator+(int i, Complex c) => AddInt(c, i);
public static int operator+(Complex c, int i) => AddInt(c, i);
private static int AddInt(Complex c, int i) => c.X + i;
关于c# - 为什么运算符方法在 C# 中应该是静态的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57484988/