首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

C# 複數類別設計:Display 方法回傳型別與實作建議

     編輯:程式設計疑難解答

核心結論

.NET 基礎類別庫(BCL)內建不支援複數型別(直到 .NET 8 仍無 System.Numerics.Complex 的完整格式化支援)。開發者需自行定義結構體或類別,Display 方法的回傳型別由設計者決定。

推薦設計模式

1. 不可變結構體 + 覆寫 ToString(最符合 .NET 慣例)

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";
    }

    // 運算子多載、靜態工廠方法...
}

2. 靜態工廠 + 格式化選項

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(支援標準格式字串)

參考資源

總結

  • Display 回傳 string 最直觀,便於 UI 直接繫結。
  • 實作 IFormattable 可支援 ToString("F2") 等標準格式化。
  • 若專案需大量數學運算,直接引用 MathNet.Numerics 而非重造輪子。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved