其他类中的运算符重载

Lav*_*let 4 c#

我可以在 C# 中为 B 类中的 A 类重载运算符吗?例如:

class A
{
}

class B
{
    public static A operator+(A x, A y)
    {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

jas*_*son 5

不; 参数之一必须是包含类型。

来自语言规范(版本 4.0)的第 10.10.2 节:

以下规则适用于二元运算符声明,其中T表示包含运算符声明的类或结构的实例类型:

• 二元非移位运算符必须采用两个参数,其中至少一个必须具有类型TT?,并且可以返回任何类型。

你应该想想为什么。这是一个原因。

class A { }
class B { public static A operator+(A first, A second) { // ... } }
class C { public static A operator+(A first, A second) { // ... } }

A first;
A second;
A result = first + second; // which + ???
Run Code Online (Sandbox Code Playgroud)

这是另一个:

class A { public static int operator+(int first, int second) { // ... } } 
Run Code Online (Sandbox Code Playgroud)

假设这允许了一会儿。

int first = 17;
int second = 42;
int result = first + second;
Run Code Online (Sandbox Code Playgroud)

根据运算符重载解析规范(第 7.3.2 节),A.+将优先于Int32.+. 我们刚刚为ints重新定义了加法!可恶的。