C# 运算符重载(Operator Overloading)
本章节是关于 C# 运算符重载(Operator Overloading) 的全面、详细、专业解释,包含语法机制、适用规则、示例代码、使用场景、注意事项以及权威官方文档链接。
1. 什么是运算符重载?
在 C# 中,运算符(如 +、-、*、== 等)可以被 重载,使其能在自定义类型(如类或结构体)上实现特定的运算行为。
🔍 目的:增强自定义类型的可读性和可用性,模仿内置类型操作。
2. 支持重载的运算符
以下是 C# 中 允许重载 的运算符:
✔️ 一元运算符(Unary)
+、-、!、~、++、--、true、false
✔️ 二元运算符(Binary)
+、-、*、/、%、&、|、^、<<、>>、==、!=、>、<、>=、<=
❌ 不可重载:
=、&&、||、[](索引器可通过属性实现)、()(调用)、.、?:、new、is、as
3. 运算符重载语法
通用语法格式:
public static 返回类型 operator 运算符(参数列表) {
// 实现
}
4. 示例:重载 + 运算符
public class Vector {
public int X { get; set; }
public int Y { get; set; }
public Vector(int x, int y) {
X = x;
Y = y;
}
public static Vector operator +(Vector a, Vector b) {
return new Vector(a.X + b.X, a.Y + b.Y);
}
public override string ToString() => $"({X}, {Y})";
}
使用:
var v1 = new Vector(2, 3);
var v2 = new Vector(4, 1);
var result = v1 + v2; // 调用 operator + 方法
Console.WriteLine(result); // 输出: (6, 4)
5. 示例:重载 == 和 != 运算符(必须配合 Equals 与 GetHashCode)
public class Point {
public int X, Y;
public Point(int x, int y) {
X = x; Y = y;
}
public static bool operator ==(Point a, Point b) {
if (ReferenceEquals(a, b)) return true;
if (a is null || b is null) return false;
return a.X == b.X && a.Y == b.Y;
}
public static bool operator !=(Point a, Point b) => !(a == b);
public override bool Equals(object obj) =>
obj is Point p && this == p;
public override int GetHashCode() =>
HashCode.Combine(X, Y);
}
6. 示例:重载 ++ 运算符
public class Counter {
public int Value { get; set; }
public static Counter operator ++(Counter c) {
c.Value++;
return c;
}
}
7. 实战应用场景
| 场景 | 运算符 |
|---|---|
| 数学类库(如 Vector、Matrix) | +, -, *, / |
| 单位转换(如重量、长度) | 比较运算符 <, > |
| 计数器类 | ++, -- |
| 自定义数据结构(如 Complex, Money) | ==, !=, + |
8. 注意事项与限制
| 项目 | 说明 |
|---|---|
必须是 static | 所有运算符重载方法都必须是 public static |
| 至少有一个操作数是当前类 | 防止对系统类型重载 |
| 建议成对实现 | 如重载 == 就必须重载 != |
重写 Equals 与 GetHashCode | 当重载比较运算符时,推荐一并实现 |
| 谨慎使用重载 | 过度重载会使代码可读性下降 |
9. 官方文档与权威资料
- Operator Overloading – Microsoft Learn
- C# Operators – Microsoft Docs
- Equality Operators == and != – Microsoft
10. 总结表格
| 特性 | 说明 |
|---|---|
| 支持类型 | 类(class)、结构体(struct) |
| 关键字 | operator |
| 返回类型 | 通常为类类型或布尔值 |
| 与重载配套 | Equals() 和 GetHashCode() |
更多详细内容,请关注其他相关文章!