Initial Obsidian notes backup
This commit is contained in:
@@ -0,0 +1,86 @@
|
||||
概念:
|
||||
==让自定义类和结构体能够使用运算符==
|
||||
让自定义类结构体可以进行运算
|
||||
通常需要注意运算符需要几个参数,例如取反只有一个参数,加有两个参数
|
||||
可重载的运算符:
|
||||
- 算数运算符
|
||||
- 逻辑运算符==非==
|
||||
- 位运算符
|
||||
- 条件运算符
|
||||
不可重载的运算符:
|
||||
- 逻辑与(&&)逻辑或(||)
|
||||
- 索引符\[]
|
||||
- 墙砖运算符()
|
||||
- 点.
|
||||
- 三目运算符: ?
|
||||
- 赋值符=
|
||||
|
||||
|
||||
通常用法:
|
||||
|
||||
|
||||
语法:
|
||||
使用关键词operator
|
||||
作为类的一个成员存在
|
||||
public static 返回值类型 operator 运算符(参数列表)
|
||||
|
||||
案例:
|
||||
```Csharp
|
||||
class Point
|
||||
{
|
||||
public int x;
|
||||
public int y;
|
||||
|
||||
public static Point operator +(Point p1, Point p2)
|
||||
{
|
||||
Point newPoint = new Point();
|
||||
newPoint.x = p1.x + p2.x;
|
||||
newPoint.y = p1.y + p2.y;
|
||||
|
||||
return newPoint;
|
||||
}
|
||||
|
||||
public static Point operator +(Point p1, int value)
|
||||
{
|
||||
Point newPoint = new Point();
|
||||
newPoint.x = p1.x + value;
|
||||
newPoint.y = p1.y + value;
|
||||
return newPoint;
|
||||
}
|
||||
}
|
||||
|
||||
class Program
|
||||
{
|
||||
public static void Main(string[] args)
|
||||
{
|
||||
Point p1 = new Point();
|
||||
p1.x = 1;
|
||||
p1.y = 1;
|
||||
|
||||
Point p2 = new Point();
|
||||
p2.x = 2;
|
||||
p2.y = 2;
|
||||
|
||||
Point p3 = new Point();
|
||||
p3 = p1 + p2;
|
||||
Console.WriteLine(p3.x);
|
||||
|
||||
p3 = null;
|
||||
p3 = p1 + 10;
|
||||
Console.WriteLine(p3.x);
|
||||
}
|
||||
|
||||
}
|
||||
```
|
||||
第一个运算符重载了`+`号,可以让这个类的两个实例化对象相加
|
||||
第二个运算符也重载了`+`号,可以让这个类加上一个value
|
||||
==如果需要value在前也需要进行一次重载!!!==
|
||||
|
||||
|
||||
注意:
|
||||
1. 一定是公共的静态方法
|
||||
2. 返回值写在operator前
|
||||
3. 逻辑处理自定义
|
||||
4. 一个符号可以多个重载
|
||||
5. 不能使用ref和out
|
||||
6. ==条件运算符需要成对实现==
|
||||
Reference in New Issue
Block a user