IFormattable.ToString(String, IFormatProvider) 方法


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

 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



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

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


要用來格式化值的提供者。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.", 
      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";
            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.", _
      Me.temp = temperature
   End Sub
   Public ReadOnly Property Celsius As Decimal
         Return temp
      End Get
   End Property
   Public ReadOnly Property Fahrenheit As Decimal
         Return temp * 9 / 5 + 32
      End Get
   End Property
   Public ReadOnly Property Kelvin As Decimal
         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提供者或自訂格式提供者null的方法傳回時, 複合格式方法才會呼叫物件的執行。An 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.