IFormattable.ToString(String, IFormatProvider) IFormattable.ToString(String, IFormatProvider) IFormattable.ToString(String, IFormatProvider) IFormattable.ToString(String, IFormatProvider) Method

定義

使用指定的格式,格式化目前執行個體的值。Formats the value of the current instance using the specified format.

public:
 System::String ^ ToString(System::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

參數

format
String String String String

要使用的格式。The format to use.

-或--or- Null 參考 (在 Visual Basic 中為 Nothing),用於使用針對 IFormattable 實作而定義的預設格式。A null reference (Nothing in Visual Basic) to use the default format defined for the type of the IFormattable implementation.

formatProvider
IFormatProvider IFormatProvider IFormatProvider IFormatProvider

要用來格式化值的提供者。The provider to use to format the value.

-或--or- Null 參考 (在 Visual Basic 中為 Nothing),用於取得作業系統目前地區設定中的數值格式資訊。A null reference (Nothing in Visual Basic) to obtain the numeric format information from the current locale setting of the operating system.

傳回

採用指定格式之目前執行個體的值。The value of the current instance in the specified format.

範例

下列範例示範Temperature可實作類別ToString方法。The following example demonstrates a Temperature class that implements the ToString method. 此程式碼範例是針對提供之較大範例的一部分IFormattable類別。This code example is part of a larger example provided for the IFormattable class.

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));
      }
   }
}
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

備註

ToString方法會將值轉換成可以多種方式表示的字串表示。The ToString method converts a value to a string representation that can be expressed in multiple ways. 其精準的格式取決於特定符號或指定的順序,由特定文化特性、 職業、 或產業所定義。Its precise format depends on specific symbols or a specified order defined by specific cultures, professions, or industries. 您可以直接呼叫方法。You can call the method directly. 它也稱為自動Convert.ToString(Object)Convert.ToString(Object, IFormatProvider)方法,藉由使用複合格式化方法的功能在.NET Framework 中,例如String.Format(String, Object[])Console.WriteLine(String, Object[]),和StringBuilder.AppendFormat(String, Object[])It is also called automatically by the Convert.ToString(Object) and Convert.ToString(Object, IFormatProvider) methods, and by methods that use the composite formatting feature in the .NET Framework, such as String.Format(String, Object[]), Console.WriteLine(String, Object[]), and StringBuilder.AppendFormat(String, Object[]). (如需詳細資訊,請參閱 < 複合格式。)(For more information, see Composite Formatting.)

複合格式化方法會呼叫ToString方法一次在格式字串中的每個格式項目。Composite formatting methods call the ToString method once for each format item in a format string. 傳遞給方法的參數,如下所示依據特定的格式化方法的呼叫以及格式項目的內容:The parameters passed to the method depend on the specific formatting method that is called and on the content of the format item, as follows:

注意

物件的ToString實作會呼叫複合格式方法未傳遞時,才ICustomFormatter格式提供者,或如果Format自訂格式提供者方法的傳回nullAn object's ToString implementation is called by composite formatting methods only if they are not passed an ICustomFormatter format provider, or if the Format method of the custom format provider returns null.

.NET Framework 包含三種格式提供者,當然也實作IFormatProvider介面:The .NET Framework includes three format providers, all of which implement the IFormatProvider interface:

  • NumberFormatInfo 會提供數值格式資訊,例如代表小數點的使用、 群組分隔符號字元和拼字和貨幣值中的貨幣符號的位置。NumberFormatInfo supplies numeric formatting information, such as the characters to use for decimal and group separators, and the spelling and placement of currency symbols in monetary values.

  • DateTimeFormatInfo 提供相關的日期和時間相關格式資訊,例如月、 日和年的日期模式中的位置。DateTimeFormatInfo supplies date-related and time-related formatting information, such as the position of the month, the day, and the year in a date pattern.

  • CultureInfo 包含預設的格式化特定文化特性,包括數值格式資訊中的資訊和相關的日期和時間相關的格式資訊。CultureInfo contains the default formatting information in a specific culture, including the numeric format information, and date-related and time-related formatting information.

此外,您可以定義自己的自訂格式提供者。In addition, you can define your own custom format provider.

給實施者的注意事項

ToString(String, IFormatProvider)方法必須支援"G"(一般) 格式規範。The ToString(String, IFormatProvider) method must support the "G" (general) format specifier. "G"規範,除了類別可以定義它所支援的格式規範的清單。Besides the "G" specifier, the class can define the list of format specifiers that it supports. 此外,類別必須準備好處理格式規範所nullIn addition, the class must be prepared to handle a format specifier that is null. 如需有關格式設定和格式化程式碼的詳細資訊,請參閱格式化型別For more information about formatting and formatting codes, see Formatting Types.

適用於

另請參閱