首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

Effective C# 原則 5:永遠提供 ToString()(下)

     編輯:關於C語言

IFormattable 進階格式化支援

實作 IFormattable 讓型別支援自訂格式字串:

public class Customer : IFormattable
{
    public string Name { get; }
    public decimal Revenue { get; }
    public string ContactPhone { get; }

    // 標準 ToString
    public override string ToString() => Name;

    // IFormattable.ToString
    public string ToString(string format, IFormatProvider formatProvider)
    {
        if (formatProvider != null)
        {
            var formatter = formatProvider.GetFormat(GetType()) as ICustomFormatter;
            if (formatter != null)
                return formatter.Format(format, this, formatProvider);
        }

        return format?.ToUpperInvariant() switch
        {
            "N" => Name,
            "R" => Revenue.ToString("C"),
            "P" => ContactPhone,
            "NR" => $"{Name,20}, {Revenue,10:C}",
            "NP" => $"{Name,20}, {ContactPhone,15}",
            "NPR" => $"{Name,20}, {ContactPhone,15}, {Revenue,10:C}",
            "G" or "" or null => Name,
            _ => Name
        };
    }
}

自訂格式化提供者(ICustomFormatter + IFormatProvider)

public class CustomerFormatProvider : IFormatProvider, ICustomFormatter
{
    public object GetFormat(Type formatType)
        => formatType == typeof(ICustomFormatter) ? this : null;

    public string Format(string format, object arg, IFormatProvider formatProvider)
    {
        if (arg is not Customer c) return arg.ToString();

        return format?.ToUpperInvariant() switch
        {
            "LONG" => $"{c.Name,50}, {c.ContactPhone,15}, {c.Revenue,10:C}",
            _ => c.ToString(format, formatProvider)
        };
    }
}

// 使用方式
var formatter = new CustomerFormatProvider();
Console.WriteLine(string.Format(formatter, "{0:LONG}", customer));

呼叫端視角:當型別不支援你要的格式

若庫型別未實作你需要的格式,可自行實作 IFormatProvider + ICustomFormatter 外掛支援,無須修改原型別。

核心建議總結

  1. 永遠覆寫 Object.ToString():回傳最常用、最具辨識度的字串表示
  2. 實作 IFormattable:支援多種格式化需求(報表、匯出、日誌)
  3. 支援標準格式:"G"、""、null 應回傳相同結果
  4. 大小寫不敏感:格式字串比較用 ToUpperInvariant()
  5. 委派給 ICustomFormatter:讓外部擴充格式而不修改型別

實用模板

public override string ToString() => $"{Name} (ID: {Id})";

public string ToString(string format, IFormatProvider provider)
{
    if (provider?.GetFormat(GetType()) is ICustomFormatter fmt)
        return fmt.Format(format, this, provider);

    return format?.ToUpperInvariant() switch
    {
        "D" => DetailedFormat(),
        "S" => ShortFormat(),
        _ => ToString()
    };
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved