實作 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
};
}
}
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 外掛支援,無須修改原型別。
Object.ToString():回傳最常用、最具辨識度的字串表示IFormattable:支援多種格式化需求(報表、匯出、日誌)ToUpperInvariant()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()
};
}