在c#中实现运算符重载,需要在类或结构体内部定义使用 operator 关键字的静态方法。通过指定操作符(如 +、-)和参数类型,你可以自定义对象之间的运算行为,使代码更直观且符合领域模型。

ComplexNumber 类的加法与减法如何定义?
以复数类为例,可以通过定义 operator + 和 operator - 来实现复数的加减法。这两个方法接收两个 ComplexNumber 实例作为参数,并返回一个新的 ComplexNumber 实例,其属性为输入参数的对应分量运算结果。

public struct ComplexNumber
{
public double Real { get; }
public double Imaginary { get; }
public ComplexNumber(double real, double imaginary)
{
Real = real;
Imaginary = imaginary;
}
public static ComplexNumber operator +(ComplexNumber a, ComplexNumber b)
{
return new ComplexNumber(a.Real + b.Real, a.Imaginary + b.Imaginary);
}
public static ComplexNumber operator -(ComplexNumber a, ComplexNumber b)
{
return new ComplexNumber(a.Real - b.Real, a.Imaginary - b.Imaginary);
}
public override string ToString() => $"{Real} + {Imaginary}i";
}
class Program
{
static void Main()
{
var c1 = new ComplexNumber(3, 4);
var c2 = new ComplexNumber(1, 2);
var sum = c1 + c2;
var diff = c1 - c2;
System.Console.WriteLine($"Sum: {sum}");
System.Console.WriteLine($"Diff: {diff}");
}
}运行上述代码将输出:
Sum: 4 + 6i
Diff: 2 + 2i
相等性比较运算符 == 和 != 需要满足什么约束?
当重载 == 和 != 时,必须同时重载两者,并且建议重写 Equals 和 GetHashCode 方法以保持语义一致性。此外,如果类引用类型,还需考虑重载 Equals 的行为。对于值类型,编译器会自动处理一些默认行为,但显式定义能确保逻辑清晰。

public struct ComplexNumber
{
public double Real { get; }
public double Imaginary { get; }
public ComplexNumber(double real, double imaginary)
{
Real = real;
Imaginary = imaginary;
}
public static bool operator ==(ComplexNumber a, ComplexNumber b)
{
return a.Real == b.Real && a.Imaginary == b.Imaginary;
}
public static bool operator !=(ComplexNumber a, ComplexNumber b)
{
return !(a == b);
}
public override bool Equals(object obj)
{
if (!(obj is ComplexNumber)) return false;
var other = (ComplexNumber)obj;
return Real == other.Real && Imaginary == other.Imaginary;
}
public override int GetHashCode() => HashCode.Combine(Real, Imaginary);
}
class Program
{
static void Main()
{
var c1 = new ComplexNumber(1, 2);
var c2 = new ComplexNumber(1, 2);
var c3 = new ComplexNumber(3, 4);
System.Console.WriteLine(c1 == c2); // True
System.Console.WriteLine(c1 == c3); // False
}
}运行上述代码将输出:
True
False
如果尝试对未重载的操作符进行运算会发生什么?
如果在类中没有定义某个操作符的重载方法,而代码中却尝试使用该操作符作用于该类型的实例,编译器会报错。例如,如果 ComplexNumber 没有定义 * 运算符,那么 c1 * c2 这样的表达式将无法编译通过。这确保了类型系统的安全性,防止意外的行为。


















