如何写一个运算符?

MrP*_*ram 2 c# operators

class Test
{
    public int a { get; set; }
    public int b { get; set; }

    public Test(int a, int b)
    {
        this.a = a;
        this.b = b;
    }

    public static int operator +(Test a)
    {
        int test = a.a*a.b;
        return test;
    }

    public void Testa()
    {
        Test t = new Test(5, 5);
        Console.WriteLine((t.a + t.b));
    }
}
Run Code Online (Sandbox Code Playgroud)

当我调用Testa()方法时,我希望结果是5*5,但是我不知道如何使用上面的方法我写了+运算符

Jon*_*eet 7

您的方法会重载一元运算 +符.如果你写的话,你可以看到它的实际效果:

Test t = new Test(5, 5);
Console.WriteLine(+t); // Prints 25
Run Code Online (Sandbox Code Playgroud)

如果要重载二元 +运算符,则需要提供两个参数.例如:

// I strongly suggest you don't use "a" and "b"
// as parameter names when they're already (bad) property names
public static int operator +(Test lhs, Test rhs)
{
    return lhs.a * rhs.b + lhs.b * rhs.a;    
}
Run Code Online (Sandbox Code Playgroud)

然后用它作为:

public static void Main()
{
    Test x = new Test(2, 3);
    Test y = new Test(4, 5);
    Console.WriteLine(x + y); // Prints 22 (2*5 + 3*4)
}
Run Code Online (Sandbox Code Playgroud)