IFormattable.ToString(String, IFormatProvider) Metoda

Definicja

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

public:
 System::String ^ ToString(System::String ^ format, IFormatProvider ^ formatProvider);
public string ToString (string format, IFormatProvider formatProvider);
public string ToString (string? format, IFormatProvider? formatProvider);
abstract member ToString : string * IFormatProvider -> string
Public Function ToString (format As String, formatProvider As IFormatProvider) As String

Parametry

format
String

Format do użycia.

-lub- Odwołanie o wartości null (Nothingw Visual Basic) w celu użycia domyślnego formatu zdefiniowanego dla typu implementacjiIFormattable.

formatProvider
IFormatProvider

Dostawca, który ma służyć do formatowania wartości.

-lub- Odwołanie o wartości null (Nothingw Visual Basic) umożliwiające uzyskanie informacji o formacie liczbowym z bieżącego ustawienia regionalnego systemu operacyjnego.

Zwraca

String

Wartość bieżącego wystąpienia w określonym formacie.

Przykłady

W poniższym przykładzie pokazano klasę Temperature , która implementuje metodę ToString . Ten przykład kodu jest częścią większego przykładu udostępnionego IFormattable dla klasy .

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));
      }
   }
}
open System
open System.Globalization

type Temperature(temperature: decimal) =
    do 
        if temperature < -273.15M then
            raise (ArgumentOutOfRangeException $"{temperature} is less than absolute zero.")

    member _.Celsius =
        temperature

    member _.Fahrenheit =
        temperature * 9M / 5M + 32M

    member _.Kelvin =
        temperature + 273.15m

    override this.ToString() =
        this.ToString("G", CultureInfo.CurrentCulture)

    member this.ToString(format) =
        this.ToString(format, CultureInfo.CurrentCulture)

    member this.ToString(format, provider: IFormatProvider) =
        let format =
            if String.IsNullOrEmpty format then "G"
            else format

        let provider =
            if isNull provider then 
                CultureInfo.CurrentCulture :> IFormatProvider
            else provider

        match format.ToUpperInvariant() with
        | "G" | "C" ->
            temperature.ToString("F2", provider) + " °C"
        | "F" ->
            this.Fahrenheit.ToString("F2", provider) + " °F"
        | "K" ->
            this.Kelvin.ToString("F2", provider) + " K"
        | _ ->
            raise (FormatException $"The {format} format string is not supported.")

    interface IFormattable with
        member this.ToString(format, provider) = this.ToString(format, provider)
Imports System.Globalization

Public Class Temperature : Implements IFormattable
   Private temp As Decimal
   
   Public Sub New(temperature As Decimal)
      If temperature < -273.15 Then _ 
        Throw New ArgumentOutOfRangeException(String.Format("{0} is less than absolute zero.", _
                                              temperature))
      Me.temp = temperature
   End Sub
   
   Public ReadOnly Property Celsius As Decimal
      Get
         Return temp
      End Get
   End Property
   
   Public ReadOnly Property Fahrenheit As Decimal
      Get
         Return temp * 9 / 5 + 32
      End Get
   End Property
   
   Public ReadOnly Property Kelvin As Decimal
      Get
         Return temp + 273.15d
      End Get
   End Property

   Public Overrides Function ToString() As String
      Return Me.ToString("G", CultureInfo.CurrentCulture)
   End Function
      
   Public Overloads Function ToString(fmt As String) As String
      Return Me.ToString(fmt, CultureInfo.CurrentCulture)
   End Function
   
   Public Overloads Function ToString(fmt As String, provider As IFormatProvider) _
                   As String _
                   Implements IFormattable.ToString
      If String.IsNullOrEmpty(fmt) Then fmt = "G"
      If provider Is Nothing Then provider = CultureInfo.CurrentCulture
      
      Select Case fmt.ToUpperInvariant()
         Case "G", "C"
            Return temp.ToString("F2", provider) + " °C" 
         Case "F"
            Return Fahrenheit.ToString("F2", provider) + " °F"
         Case "K"
            Return Kelvin.ToString("F2", provider) + " K"
         Case Else
            Throw New FormatException(String.Format("The {0} format string is not supported.", fmt))
      End Select
   End Function
End Class

Uwagi

Metoda ToString konwertuje wartość na reprezentację ciągu, która może być wyrażona na wiele sposobów. Jego dokładny format zależy od konkretnych symboli lub określonego porządku zdefiniowanego przez określone kultury, zawody lub branże. Metodę można wywołać bezpośrednio. Jest ona również wywoływana automatycznie przez Convert.ToString(Object) metody i Convert.ToString(Object, IFormatProvider) oraz przez metody, które używają funkcji formatowania złożonego w .NET Framework, takich jak String.Format(String, Object[]), Console.WriteLine(String, Object[])i StringBuilder.AppendFormat(String, Object[]). (Aby uzyskać więcej informacji, zobacz Formatowanie złożone).

Metody formatowania złożonego wywołają metodę ToString raz dla każdego elementu formatu w ciągu formatu. Parametry przekazywane do metody zależą od określonej metody formatowania, która jest wywoływana i od zawartości elementu formatu, w następujący sposób:

Uwaga

Implementacja obiektu jest wywoływana ToString przez metody formatowania złożonego tylko wtedy, gdy nie są przekazywane ICustomFormatter dostawcy formatu lub jeśli Format metoda niestandardowego dostawcy formatu zwraca wartość null.

.NET Framework obejmuje trzech dostawców formatu, z których wszystkie implementują IFormatProvider interfejs:

  • NumberFormatInfo dostarcza informacje o formatowaniu liczbowym, takie jak znaki do użycia w separatorach dziesiętnych i grupowych, a także pisownię i umieszczanie symboli waluty w wartościach pieniężnych.

  • DateTimeFormatInfo dostarcza informacje o formatowaniu związane z datą i godziną, takie jak położenie miesiąca, dzień i rok w wzorcu daty.

  • CultureInfo Zawiera domyślne informacje o formatowaniu w określonej kulturze, w tym informacje o formacie liczbowym oraz informacje dotyczące formatowania związane z datą i godziną.

Ponadto można zdefiniować własnego niestandardowego dostawcę formatu.

Uwagi dotyczące implementowania

Metoda ToString(String, IFormatProvider) 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.

Dotyczy

Zobacz też