C# 內建 System.Numerics.Complex (需引用 System.Numerics.dll),但若需自定結構體,可參考以下完整範例:
public struct Complex {
public double Real;
public double Imaginary;
public Complex(double real, double imaginary) {
Real = real; Imaginary = imaginary;
}
// 運算子多載:加法
public static Complex operator +(Complex a, Complex b) {
return new Complex(a.Real + b.Real, a.Imaginary + b.Imaginary);
}
// 運算子多載:減法、乘法、除法可類似實現
public override string ToString() {
// 標準格式:a + bi 或 a - bi
string sign = Imaginary >= 0 ? "+" : "";
return $"{Real} {sign} {Imaginary}i";
}
}
// 使用範例
var c1 = new Complex(2, 3);
var c2 = new Complex(3, 4);
var sum = c1 + c2; // (5, 7)
Console.WriteLine(sum); // 輸出 "5 + 7i"
struct 為值型別,避免堆積分配,適合輕量數學物件。operator + 必須 public static,回傳新實例,不修改運算元。==/!=、Equals/GetHashCode、IFormattable 以利集合與格式化。System.Numerics.Complex,經過優化且支援更多數學函數。