.NET 基礎類別庫(BCL)內建不支援複數型別(直到 .NET 8 仍無 System.Numerics.Complex 的完整格式化支援)。開發者需自行定義結構體或類別,Display 方法的回傳型別由設計者決定。
public readonly struct Complex : IFormattable, IEquatable<Complex> {
public double Real { get; }
public double Imaginary { get; }
public Complex(double real, double imaginary) {
Real = real; Imaginary = imaginary;
}
public override string ToString() => ToString("G", CultureInfo.CurrentCulture);
public string ToString(string format, IFormatProvider provider) {
var r = Real.ToString(format, provider);
var i = Imaginary.ToString(format, provider);
return Imaginary < 0 ? $"{r} - {-Imaginary}i" : $"{r} + {i}i";
}
// 運算子多載、靜態工廠方法...
}
public static class ComplexFormat {
public static string Display(this Complex c, ComplexFormatStyle style = ComplexFormatStyle.Standard) {
return style switch {
ComplexFormatStyle.Standard => $"{c.Real} + {c.Imaginary}i",
ComplexFormatStyle.Polar => $"{c.Magnitude} ∠ {c.Phase} rad",
ComplexFormatStyle.Engineering => $"{c.Real} {c.Imaginary:+#;-#;0}j", // 電機工程用 j
_ => c.ToString()
};
}
}
public enum ComplexFormatStyle { Standard, Polar, Engineering }
var z = new Complex(3, -4);
Console.WriteLine(z.Display()); // 3 - 4i
Console.WriteLine(z.Display(ComplexFormatStyle.Polar)); // 5 ∠ -0.927 rad
Console.WriteLine(z.ToString("F2")); // 3.00 - 4.00i(支援標準格式字串)
IFormattable 可支援 ToString("F2") 等標準格式化。