Przeczytaj w języku angielskim

Udostępnij za pośrednictwem


IFormattable Interfejs

Definicja

Udostępnia funkcje formatowania wartości obiektu w reprezentacji ciągu.

C#
public interface IFormattable
C#
[System.Runtime.InteropServices.ComVisible(true)]
public interface IFormattable
Pochodne
Atrybuty

Przykłady

W poniższym przykładzie zdefiniowano klasę Temperature , która implementuje IFormattable interfejs. Klasa obsługuje cztery specyfikatory formatu: "G" i "C", które wskazują, że temperatura ma być wyświetlana w stopniach Celsjusza; "F", który wskazuje, że temperatura ma być wyświetlana w Fahrenheit; i "K", co wskazuje, że temperatura ma być wyświetlana w Kelvin. Ponadto implementacja IFormattable.ToString może również obsługiwać ciąg formatu, który jest lub pusty null . Pozostałe dwie ToString metody zdefiniowane przez klasę Temperature po prostu zawijają wywołanie implementacji IFormattable.ToString .

C#
using System;
using System.Globalization;

public class Temperature : IFormattable
{
   private decimal temp;

   public Temperature(decimal temperature)
   {
      if (temperature < -273.15m)
        throw new ArgumentOutOfRangeException(String.Format("{0} is less than absolute zero.",
                                              temperature));
      this.temp = temperature;
   }

   public decimal Celsius
   {
      get { return temp; }
   }

   public decimal Fahrenheit
   {
      get { return temp * 9 / 5 + 32; }
   }

   public decimal Kelvin
   {
      get { return temp + 273.15m; }
   }

   public override string ToString()
   {
      return this.ToString("G", CultureInfo.CurrentCulture);
   }

   public string ToString(string format)
   {
      return this.ToString(format, CultureInfo.CurrentCulture);
   }

   public string ToString(string format, IFormatProvider provider)
   {
      if (String.IsNullOrEmpty(format)) format = "G";
      if (provider == null) provider = CultureInfo.CurrentCulture;

      switch (format.ToUpperInvariant())
      {
         case "G":
         case "C":
            return temp.ToString("F2", provider) + " °C";
         case "F":
            return Fahrenheit.ToString("F2", provider) + " °F";
         case "K":
            return Kelvin.ToString("F2", provider) + " K";
         default:
            throw new FormatException(String.Format("The {0} format string is not supported.", format));
      }
   }
}

Poniższy przykład wywołuje implementację IFormattable.ToString bezpośrednio lub przy użyciu ciągu formatu złożonego.

C#
public class Example
{
   public static void Main()
   {
      // Use composite formatting with format string in the format item.
      Temperature temp1 = new Temperature(0);
      Console.WriteLine("{0:C} (Celsius) = {0:K} (Kelvin) = {0:F} (Fahrenheit)\n", temp1);

      // Use composite formatting with a format provider.
      temp1 = new Temperature(-40);
      Console.WriteLine(String.Format(CultureInfo.CurrentCulture, "{0:C} (Celsius) = {0:K} (Kelvin) = {0:F} (Fahrenheit)", temp1));
      Console.WriteLine(String.Format(new CultureInfo("fr-FR"), "{0:C} (Celsius) = {0:K} (Kelvin) = {0:F} (Fahrenheit)\n", temp1));

      // Call ToString method with format string.
      temp1 = new Temperature(32);
      Console.WriteLine("{0} (Celsius) = {1} (Kelvin) = {2} (Fahrenheit)\n",
                        temp1.ToString("C"), temp1.ToString("K"), temp1.ToString("F"));

      // Call ToString with format string and format provider
      temp1 = new Temperature(100)      ;
      NumberFormatInfo current = NumberFormatInfo.CurrentInfo;
      CultureInfo nl = new CultureInfo("nl-NL");
      Console.WriteLine("{0} (Celsius) = {1} (Kelvin) = {2} (Fahrenheit)",
                        temp1.ToString("C", current), temp1.ToString("K", current), temp1.ToString("F", current));
      Console.WriteLine("{0} (Celsius) = {1} (Kelvin) = {2} (Fahrenheit)",
                        temp1.ToString("C", nl), temp1.ToString("K", nl), temp1.ToString("F", nl));
   }
}
// The example displays the following output:
//    0.00 °C (Celsius) = 273.15 K (Kelvin) = 32.00 °F (Fahrenheit)
//
//    -40.00 °C (Celsius) = 233.15 K (Kelvin) = -40.00 °F (Fahrenheit)
//    -40,00 °C (Celsius) = 233,15 K (Kelvin) = -40,00 °F (Fahrenheit)
//
//    32.00 °C (Celsius) = 305.15 K (Kelvin) = 89.60 °F (Fahrenheit)
//
//    100.00 °C (Celsius) = 373.15 K (Kelvin) = 212.00 °F (Fahrenheit)
//    100,00 °C (Celsius) = 373,15 K (Kelvin) = 212,00 °F (Fahrenheit)

Uwagi

Interfejs IFormattable konwertuje obiekt na jego reprezentację ciągu na podstawie ciągu formatu i dostawcy formatu.

Ciąg formatu zwykle definiuje ogólny wygląd obiektu. Na przykład .NET Framework obsługuje następujące elementy:

Możesz również zdefiniować własne ciągi formatu do obsługi formatowania typów zdefiniowanych przez aplikację.

Dostawca formatu zwraca obiekt formatowania, który zwykle definiuje symbole używane podczas konwertowania obiektu na jego reprezentację ciągu. Na przykład podczas konwertowania liczby na wartość waluty dostawca formatu definiuje symbol waluty wyświetlany w ciągu wynikowym. .NET Framework definiuje trzech dostawców formatu:

Ponadto można zdefiniować własnych niestandardowych dostawców formatów, aby dostarczać informacje specyficzne dla kultury, specyficzne dla zawodu lub branżowe używane w formatowaniu. Aby uzyskać więcej informacji na temat implementowania formatowania niestandardowego przy użyciu niestandardowego dostawcy formatów, zobacz ICustomFormatter.

Interfejs IFormattable definiuje jedną metodę , ToStringktóra dostarcza usługi formatowania dla typu implementowania. Metodę ToString można wywołać bezpośrednio. Ponadto jest ona wywoływana automatycznie przez Convert.ToString(Object) metody i Convert.ToString(Object, IFormatProvider) oraz za pomocą metod korzystających z funkcji formatowania złożonego w .NET Framework. Takie metody obejmują Console.WriteLine(String, Object)między innymi , String.Formati StringBuilder.AppendFormat(String, Object). Metoda jest wywoływana ToString dla każdego elementu formatu w ciągu formatu metody.

Interfejs IFormattable jest implementowany przez podstawowe typy danych.

Uwagi dotyczące implementowania

Klasy, które wymagają większej kontroli nad formatowaniem ciągów niż ToString() zapewnia, powinny implementować IFormattable.

Klasa, która implementuje IFormattable , musi obsługiwać specyfikator formatu "G" (ogólny). Oprócz specyfikatora "G" klasa może zdefiniować listę specyfikatorów formatu, które obsługuje. Ponadto klasa musi być przygotowana do obsługi specyfikatora formatu, który jest null. Aby uzyskać więcej informacji na temat formatowania i kodów formatowania, zobacz Typy formatowania

Metody

ToString(String, IFormatProvider)

Formatuje wartość bieżącego wystąpienia przy użyciu określonego formatu.

Dotyczy

Produkt Wersje
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

Zobacz też