C# operator
时间: 2023-11-22 09:50:27 浏览: 33
C#中的operator是一种重载运算符的方式,它允许我们自定义类型的运算符行为。通过operator,我们可以为自定义类型定义加、减、乘、除等运算符的行为,使得这些类型可以像内置类型一样进行运算。以下是一个自定义类型的operator例子:
```csharp
public class Complex
{
public int Real { get; set; }
public int Imaginary { get; set; }
public Complex(int real, int imaginary)
{
Real = real;
Imaginary = imaginary;
}
public static Complex operator +(Complex c1, Complex c2)
{
return new Complex(c1.Real + c2.Real, c1.Imaginary + c2.Imaginary);
}
}
// 使用自定义类型的运算符
Complex c1 = new Complex(1, 2);
Complex c2 = new Complex(3, 4);
Complex c3 = c1 + c2;
Console.WriteLine($"({c1.Real}+{c1.Imaginary}i) + ({c2.Real}+{c2.Imaginary}i) = ({c3.Real}+{c3.Imaginary}i)");
// 输出:(1+2i) + (3+4i) = (4+6i)
```
在上面的例子中,我们定义了一个Complex类,并为它定义了一个加法运算符+的行为。当我们使用+运算符对两个Complex类型的对象进行运算时,实际上是调用了我们自定义的+运算符方法。