CKTIS / C#
Własne formatowanie w .NET: dostawca, formater i typ wartości
Rozróżnij trzy kontrakty formatowania: wyszukiwanie usługi, przechwytywanie elementu formatu i tworzenie tekstu przez sam typ wartości.
Wersja: C# 12 and .NET 8; later runtimes may add compatible features
Składnia
C# 12 / .NET 8, namespace System
IFormatProvider: object? GetFormat(Type? formatType);
ICustomFormatter: string Format(string? format, object? arg, IFormatProvider? formatProvider);
IFormattable: string ToString(string? format, IFormatProvider? formatProvider);
Composite formatting: string.Format(provider, "{0:code}", value)
Direct call: ((IFormattable)value).ToString("G", provider)W C# 12 i .NET 8 wszystkie trzy interfejsy należą do System. W przeciążeniu string.Format przyjmującym dostawcę metoda IFormatProvider.GetFormat(Type?) otrzymuje żądanie typeof(ICustomFormatter), a nie typ formatowanej wartości. Dostawca zwraca usługę żądanego typu albo null; może zwrócić this, jeśli sam implementuje tę usługę. Znaleziony formater jest używany przez całe wywołanie.
Dla elementu {0:F2} metoda ICustomFormatter.Format otrzymuje "F2", argument o indeksie zero i dostawcę. W {0} kod formatu nie występuje, więc metoda otrzymuje null. Zwrócony tekst, nawet "", kończy formatowanie elementu. Zwrócenie null pozwala temu przeciążeniu string.Format przejść do zwykłego formatowania. Zapis null! tylko wycisza ostrzeżenie analizy nullowalności: metoda nadal zwraca null, choć jej typ zwracany to string.
Jeśli formater nie jest dostępny albo nie obsłuży elementu, w .NET 8 string.Format może najpierw spróbować użyć ISpanFormattable.TryFormat. Jeśli ta próba zostanie pominięta lub TryFormat zwróci false, dla argumentu innego niż null używane jest IFormattable.ToString(format, provider), o ile argument implementuje ten interfejs. Dla pozostałych argumentów innych niż null wywoływane jest bezparametrowe ToString(), które nie dostaje kodu formatu. Argument null, który trafia do zwykłego formatowania, jest traktowany jako pusty ciąg przed ewentualnym dopełnieniem wynikającym z wyrównania. Implementacja IFormattable powinna obsługiwać "G" i null jako format ogólny. Może zgłosić FormatException dla nieobsługiwanego kodu; string.Format może zgłosić ten sam wyjątek niezależnie, np. dla indeksu poza listą argumentów.
Bezpośrednie wywołanie dwuargumentowego ToString nie uruchamia automatycznie ICustomFormatter. Typ nadal może korzystać z dostawcy, np. aby przez GetFormat pobrać NumberFormatInfo albo DateTimeFormatInfo. Nie wywołuj ponownie string.Format z tym samym dostawcą, argumentem i kodem wewnątrz Format: możesz ponownie wejść do tego samego formatera.
Przykłady
#nullable enable
using System;
using System.Globalization;
var provider = new ReadingFormatProvider();
var reading = new Voltage(12.5m);
Console.WriteLine(string.Format(provider, "{0:bracket} | {0:F2} | {0}", reading));
sealed class ReadingFormatProvider : IFormatProvider, ICustomFormatter
{
public object? GetFormat(Type? formatType) =>
formatType == typeof(ICustomFormatter)
? this
: CultureInfo.InvariantCulture.GetFormat(formatType);
public string Format(string? format, object? arg, IFormatProvider? formatProvider)
{
if (format == "bracket" && arg is Voltage voltage)
return "[" + voltage.ToString("F2", formatProvider) + "]";
return null!; // string.Format continues with ordinary formatting.
}
}
sealed class Voltage(decimal volts) : IFormattable
{
public override string ToString() => ToString("G", null);
public string ToString(string? format, IFormatProvider? formatProvider) =>
(format switch
{
null or "G" => volts.ToString("G", formatProvider),
"F2" => volts.ToString("F2", formatProvider),
_ => throw new FormatException($"Unsupported voltage format: {format}")
}) + " V";
}Wynik
[12.50 V] | 12.50 V | 12.5 V
Formater obsługuje `bracket` dla `Voltage`, wywołując bezpośrednio `ToString("F2", formatProvider)` i dodając nawiasy kwadratowe. Dwa pozostałe elementy trafiają do `Voltage.ToString` przez ścieżkę zastępczą. Dostawca przekazuje żądania danych kulturowych do `CultureInfo.InvariantCulture`, więc separatorem dziesiętnym jest kropka.
Powiązane lekcje
- C# · Lekcja 33 · Zaawansowany · Wersja: 3