c#

运算符重载:重定义或重载 C# 中内置的运算符。因此,程序员也可以使用用户自定义类型的运算符。重载运算符是具有特殊名称的函数,是通过关键字 operator 后跟运算符的符号来定义的。与其他函数一样,重载运算符有返回类型和参数列表。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Box
{
public double Length { get; set; }
public double Width { get; set; }
public double Heigth { get; set; }
public double GetVolume()
{
return this.Length * this.Width * this.Heigth;
}
public static Box operator +(Box b, Box c)
{
var box = new Box();
box.Length = b.Length + c.Length;
box.Width = b.Width + c.Width;
box.Heigth = b.Heigth + c.Heigth;
return box;
}
}
static void Main(string[] args)
{
var box1 = new Box();
box1.Length = 10;
box1.Width = 20;
box1.Heigth = 30;
var box2 = new Box();
box2.Length = 30;
box2.Width = 40;
box2.Heigth = 50;
var box3 = box1 + box2;
Console.WriteLine(box1.GetVolume());
Console.WriteLine(box2.GetVolume());
Console.WriteLine(box3.GetVolume());
Console.ReadKey();
}