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;
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 = "";
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); } } }
|