Csharp-运算符重载

Csharp-运算符重载

运算符重载是将运算符看作方法,在类中重新定义其方法功能

注:Java中不存在此功能,如果想实现此功能则直接编写方法


双目运算符

public static 返回值类型 operator 运算符号(参数类型 参数1, 参数类型 参数2)

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
35
36
37
38
namespace Demo05
{
internal class Program
{
static void Main(string[] args)
{
var left = new Box();
left.width = 10;
left.height = 10;
left.depth = 10;

var right = new Box();
right.width = 10;
right.height = 10;
right.depth = 10;

var box = right + left;
Console.WriteLine($"新图形的长{box.height}、宽{box.width}、高{box.depth}");
}

class Box
{
public int width = 0;
public int height = 0;
public int depth = 0;

// 重载Box类的运算符+ ,使得运算符+作用于box对象时功能变换为长宽高相加
public static Box operator +(Box left, Box right)
{
var box = new Box();
box.width = left.width + right.width;
box.depth = left.depth + right.depth;
box.height = left.height + right.height;
return box;
}
}
}
}

单目运算符

public static 返回值类型 operator 运算符号(参数类型 参数1)

在c#中,-不止可以作为双目运算符的减号使用,同时可以作为单目运算符取相反数

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
namespace Demo05
{
internal class Demo01
{
public int x;
public int y;

public static Demo01 operator -(Demo01 demo01)
{
var demo = new Demo01();
demo.x = demo01.x = -demo01.x;
demo.y = demo01.y = -demo01.y;
return demo;
}

public static void Main(string[] args)
{
var demo01 = new Demo01();
demo01.x = 1;
demo01.y = 2;

var demo02 = -demo01;
Console.WriteLine($"x的相反数为:{demo02.x},y的相反数为:{demo02.y}");
}
}
}

注:一个程序可以同时存在与单目运算符-和双目运算符-,因为其参数不同,所以是重载到不同的运算符中


类型转换运算符

C#允许将显式类型转换和隐式类型转换看作运算符,并且得到重载功能

重载隐式类型转换

public static implicit operator 目标类型 (类型 待转换对象)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
namespace Demo05
{
internal class Demo02
{
public int age = 0;
public string name = "";

// 重载隐式类型转换,当对象被直接赋值整型变量时执行此方法
public static implicit operator Demo02(int age)
{
Demo02 d = new Demo02();
d.age = age;
return d;
}

public static void Main(string[] args)
{
var demo02 = new Demo02();
demo02 = 18;
}
}
}
重载显式类型转换

public static explicit operator 目标类型 (类型 待转换对象)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
namespace Demo05
{
internal class Demo02
{
public int age = 18;
public string name = "";

// 重载显式类型转换,当对象被强转为int型变量时调用此方法
public static explicit operator int(Demo02 d)
{
return d.age;
}


public static void Main(string[] args)
{
var demo02 = new Demo02();
int a = (int)demo02;

Console.WriteLine(a);
}
}
}


Csharp-运算符重载
http://blog.170827.xyz/2024/09/18/Csharp-运算符重载/
作者
XIAOBAI
发布于
2024年9月18日
许可协议