C# 其他类中的运算符重载

C# 其他类中的运算符重载,c#,C#,我可以重载C#中B类中A类的运算符吗?例如: class A { } class B { public static A operator+(A x, A y) { ... } } 没有;其中一个参数必须是包含类型 根据语言规范(版本4.0)第§10.10.2节: 以下规则适用于二进制运算符声明,其中T表示包含运算符声明的类或结构的实例类型: •二进制非移位运算符必须具有两个参数,其中至少一个参数必须具有类型T或T?,并且可以返回任何类型 你应该想想为

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

class A
{
}

class B
{
    public static A operator+(A x, A y)
    {
        ...
    }
}

没有;其中一个参数必须是包含类型

根据语言规范(版本4.0)第§10.10.2节:

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

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

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

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 + ???
还有一个:

class A { public static int operator+(int first, int second) { // ... } } 
假设这允许一段时间

int first = 17;
int second = 42;
int result = first + second;

根据操作员过载解决规范(§7.3.2),
A.+
优先于
Int32.+
。我们刚刚为
int
s重新定义了加法!讨厌。

不,你不能<代码>错误CS0563:二进制运算符的参数之一必须是包含类型

“在每种情况下,一个参数必须与声明运算符”quote from“的类或结构的类型相同
.

通常说不,但如果有帮助的话,你可以做如下事情:)


为了了解您的问题,我可以问您为什么要这样做吗?:)

有一些扩展方法。我认为运营商也有类似的情况。@Lavir:我们考虑过在C#4中添加扩展运营商,但没有这样做的预算。可能是在该语言的假设未来版本中。我想用“+”、“==”和“!=”运算符扩展IEnumerable。然后我认为您要枚举的类应该派生自System.Collections.IEnumerable。然后在你的类(从IEnumerable派生)中,你必须重载你需要的操作符,这应该可以做到。我需要比较和连接任何IEnumerable,事实上,无论它们是列表、集合还是任何其他数据结构。
class A
{
    public static A operator +(A x, A y)
    {
        A a = new A();
        Console.WriteLine("A+"); // say A
        return a;
    }
}

class B
{
    public static A operator +(A x, B y)
    {
        A a = new A();
        Console.WriteLine("return in:A,B in out:A in class B+"); // say B
        return a;
    }

    public static A operator +(B x, B y)
    {
        A a = new A();
        Console.WriteLine("return in:B,B in out:A in class B +");
        return a;
    }
    // and so on....

}


B b = new B();
A a = new A();
A a1 = new A();
B b1 = new B();

a = b + b1; // here you call operator of B, but return A
a = a + a1; // here you call operator of A and return A