C# 运算符重载
讲解 C# 用户自定义类型的运算符重载语法(public static operator)、二元算术/一元/成对比较运算符实现规范、复合赋值自动推导以及不可重载运算符边界,并在本地 csc4 实测验证。
学完这一章,你能够
- 讲解 C# 用户自定义类型的运算符重载语法(public static operator)、二元算术/一元/成对比较运算符实现规范、复合赋值自动推导以及不可重载运算符边界,并在本地 csc4 实测验证。
运算符重载语法与二元加法实现
C# 允许开发者为自定义类或结构体重新定义内置运算符的行为,使自定义类型能够像内置数值类型一样直观地参与表达式运算。重载运算符本质上是带有特殊签名的静态函数,必须同时标注 `public static`,以 `operator` 关键字紧跟目标运算符符号声明,并具备明确的返回类型与参数列表(至少一个参数必须为所在包含类型)。例如 `public static Box operator +(Box b, Box c)` 将两个 `Box` 实例的长、宽、高逐项相加并返回新的 `Box` 对象。
完整实现中,设定 `Box1(6, 7, 5)`(体积 `210`)与 `Box2(12, 13, 10)`(体积 `1560`),执行 `Box3 = Box1 + Box2` 后自动触发重载的 `+` 运算符,得到维度 `(18, 20, 15)`、体积 `5400` 的新对象。此外,一旦重载了二元 `+` 运算符,对应的复合赋值运算符 `+=` 也会由编译器自动基于 `+` 求值,本站实测 `boxAccum += box1` 精确得到 `(7, 9, 8)`。
可重载与不可重载运算符规则及完整比较实测
并非所有 C# 运算符都支持重载:常见一元运算符(`+`、`-`、`!`、`~`、`++`、`--`)、二元算术运算符(`+`、`-`、`*`、`/`、`%`)与比较运算符(`==`、`!=`、`<`、`>`、`<=`、`>=`)均允许重载;但比较运算符必须成对重载(`==` 与 `!=`、`<` 与 `>`、`<=` 与 `>=`),且重载 `==`/`!=` 时应同步重写 `Object.Equals` 与 `Object.GetHashCode` 以保持语义一致并消除编译器警告。条件逻辑运算符(`&&`、`||`)、复合赋值运算符(`+=` 等)以及成员访问/类型运算符(`=`、`.`、`?:`、`->`、`new`、`is`、`sizeof`、`typeof`)不能被直接重载。
在扩展实验中,我们为 `Box` 同时重载了 `+`、一元 `++`、一元取负 `-`、`==`、`!=`、`<`、`>`、`<=`、`>=`,并重写了 `ToString()`、`Equals()` 与 `GetHashCode()`。本站 `csc4` 实测确认 `Box1 < Box2`、`Box1 <= Box2`、`Box1 != Box2` 与 `Box3 == Box4` 均为 `True`,`Box1 > Box2` 与 `Box1 >= Box2` 均为 `False`,且一元 `++` 与 `-` 精确输出 `(3, 4, 5)` 与 `(-3, -4, -5)`。
C# 运算符可重载性分类对照表
| 运算符分组 | 重载支持与语言约束说明 |
| +, -, !, ~, ++, -- | 单操作数一元运算符,支持直接重载(另含 true/false 需成对重载) |
| +, -, *, /, % | 双操作数二元算术运算符,支持直接重载(另含位与移位运算符 &、|、^、<<、>>) |
| ==, !=, <, >, <=, >= | 比较与相等性运算符,支持重载但必须成对定义(==/!=、</>, <=/>=) |
| &&, || | 条件短路逻辑运算符,不可直接重载(需通过重载 &/| 配合 true/false 间接启用) |
| +=, -=, *=, /=, %= | 复合赋值运算符,不可单独重载,但重载对应二元运算符后编译器会自动支持 |
| =, ., ?:, ->, new, is, sizeof, typeof | 基础赋值、成员访问、条件三元、类型与内存运算符,语言规范禁止重载 |
在本地 csc4 实测 Box 二元加法、自动 +=、成对比较运算符及一元 ++/- 重载
展开查看收起
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace CSharpOperatorOverloadingLab
{
internal class Box
{
private double length;
private double breadth;
private double height;
public void SetLength(double len) { length = len; }
public void SetBreadth(double bre) { breadth = bre; }
public void SetHeight(double hei) { height = hei; }
public double GetVolume()
{
return length * breadth * height;
}
public static Box operator +(Box b, Box c)
{
Box box = new Box();
box.length = b.length + c.length;
box.breadth = b.breadth + c.breadth;
box.height = b.height + c.height;
return box;
}
public static Box operator ++(Box b)
{
Box next = new Box();
next.length = b.length + 1.0;
next.breadth = b.breadth + 1.0;
next.height = b.height + 1.0;
return next;
}
public static Box operator -(Box b)
{
Box neg = new Box();
neg.length = -b.length;
neg.breadth = -b.breadth;
neg.height = -b.height;
return neg;
}
public static bool operator ==(Box lhs, Box rhs)
{
if (object.ReferenceEquals(lhs, rhs)) return true;
if (object.ReferenceEquals(lhs, null) || object.ReferenceEquals(rhs, null)) return false;
return lhs.length == rhs.length && lhs.breadth == rhs.breadth && lhs.height == rhs.height;
}
public static bool operator !=(Box lhs, Box rhs)
{
return !(lhs == rhs);
}
public static bool operator <(Box lhs, Box rhs)
{
return lhs.length < rhs.length && lhs.breadth < rhs.breadth && lhs.height < rhs.height;
}
public static bool operator >(Box lhs, Box rhs)
{
return lhs.length > rhs.length && lhs.breadth > rhs.breadth && lhs.height > rhs.height;
}
public static bool operator <=(Box lhs, Box rhs)
{
return lhs.length <= rhs.length && lhs.breadth <= rhs.breadth && lhs.height <= rhs.height;
}
public static bool operator >=(Box lhs, Box rhs)
{
return lhs.length >= rhs.length && lhs.breadth >= rhs.breadth && lhs.height >= rhs.height;
}
public override bool Equals(object obj)
{
Box other = obj as Box;
return !object.ReferenceEquals(other, null) && (this == other);
}
public override int GetHashCode()
{
return length.GetHashCode() ^ breadth.GetHashCode() ^ height.GetHashCode();
}
public override string ToString()
{
return string.Format(CultureInfo.InvariantCulture, "({0}, {1}, {2})", length, breadth, height);
}
}
internal class Program
{
private static string Esc(string s)
{
if (s == null) return "null";
StringBuilder sb = new StringBuilder("\"");
foreach (char c in s)
{
switch (c)
{
case '\\': sb.Append("\\\\"); break;
case '"': sb.Append("\\\""); break;
case '\n': sb.Append("\\n"); break;
case '\r': sb.Append("\\r"); break;
case '\t': sb.Append("\\t"); break;
default:
if (c < 32) sb.AppendFormat("\\u{0:x4}", (int)c);
else sb.Append(c);
break;
}
}
sb.Append("\"");
return sb.ToString();
}
private static string CaseJson(string name, string summary, string expected, string actual)
{
bool passed = string.Equals(expected, actual, StringComparison.Ordinal);
return string.Format(
"{{\"name\":{0},\"summary\":{1},\"expected\":{2},\"actual\":{3},\"passed\":{4}}}",
Esc(name), Esc(summary), Esc(expected), Esc(actual), passed ? "true" : "false"
);
}
private static void Main(string[] args)
{
Console.OutputEncoding = Encoding.UTF8;
List<string> cases = new List<string>();
Box box1 = new Box();
box1.SetLength(6.0); box1.SetBreadth(7.0); box1.SetHeight(5.0);
Box box2 = new Box();
box2.SetLength(12.0); box2.SetBreadth(13.0); box2.SetHeight(10.0);
// Case 1: Binary + overloading & implicit += evaluation
Box box3 = box1 + box2;
Box boxAccum = new Box();
boxAccum.SetLength(1.0); boxAccum.SetBreadth(2.0); boxAccum.SetHeight(3.0);
boxAccum += box1;
string actual1 = string.Format(
CultureInfo.InvariantCulture,
"v1={0},v2={1},b3={2},v3={3},accum={4}",
box1.GetVolume(), box2.GetVolume(), box3.ToString(), box3.GetVolume(), boxAccum.ToString()
);
cases.Add(CaseJson(
"binary_addition_and_compound",
"验证重载二元 + 运算符实现 Box 对象相加,以及 += 自动复用重载后的 + 运算符",
"v1=210,v2=1560,b3=(18, 20, 15),v3=5400,accum=(7, 9, 8)",
actual1
));
// Case 2: Comparison & equality operators
Box box4 = box3;
string actual2 = string.Format(
"gt={0},lt={1},ge={2},le={3},ne={4},eq={5}",
box1 > box2, box1 < box2, box1 >= box2, box1 <= box2, box1 != box2, box3 == box4
);
cases.Add(CaseJson(
"comparison_and_equality_operators",
"验证成对重载的 >、<、>=、<=、==、!= 比较运算符及 ToString 输出",
"gt=False,lt=True,ge=False,le=True,ne=True,eq=True",
actual2
));
// Case 3: Unary operators (++ and unary -)
Box unit = new Box();
unit.SetLength(2.0); unit.SetBreadth(3.0); unit.SetHeight(4.0);
Box incremented = ++unit;
Box negated = -incremented;
string actual3 = string.Format("inc={0},neg={1}", incremented.ToString(), negated.ToString());
cases.Add(CaseJson(
"unary_operator_overloading",
"验证一元运算符 ++ 与一元取负 - 的重载行为",
"inc=(3, 4, 5),neg=(-3, -4, -5)",
actual3
));
Console.WriteLine(string.Format(
"{{\"version\":{0},\"cases\":[{1}]}}",
Esc("CLR " + Environment.Version.ToString()),
string.Join(",", cases.ToArray())
));
}
}
}
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
不能;C# 编译器强制要求 `==` 与 `!=` 成对重载,否则直接编译报错。同时重写 `Equals` 与 `GetHashCode` 则是为了确保基于字典/哈希集合的判等行为与 `==` 运算符一致,并消除 CS0660/CS0661 警告。