IFormattable IFormattable IFormattable IFormattable Interface

定義

提供將物件的值格式化成以字串表示的功能。Provides functionality to format the value of an object into a string representation.

public interface class IFormattable
[System.Runtime.InteropServices.ComVisible(true)]
public interface IFormattable
type IFormattable = interface
Public Interface IFormattable
衍生
屬性

範例

下列範例定義一個實作 Temperature 介面的 IFormattable 類別。The following example defines a Temperature class that implements the IFormattable interface. 類別支援四個格式規範:"G" 和 "C", 表示溫度會以攝氏顯示;"F", 表示溫度會以華氏顯示;和 "K", 這表示溫度會以「開氏」方式顯示。The class supports four format specifiers: "G" and "C", which indicate that the temperature is to be displayed in Celsius; "F", which indicates that the temperature is to be displayed in Fahrenheit; and "K", which indicates that the temperature is to be displayed in Kelvin. 此外, 此IFormattable.ToString執行也可以處理為null或空白的格式字串。In addition, the IFormattable.ToString implementation also can handle a format string that is null or empty. 類別所IFormattable.ToString定義ToString Temperature的其他兩個方法, 只會包裝對實作為的呼叫。The other two ToString methods defined by the Temperature class simply wrap a call to the IFormattable.ToString implementation.

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

接著, 下列範例會直接IFormattable.ToString呼叫此實作為, 或使用複合格式字串。The following example then calls the IFormattable.ToString implementation either directly or by using a composite format string.

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)
Module Example
   Public Sub Main()
      ' Use composite formatting with format string in the format item.
      Dim temp1 As New Temperature(0)
      Console.WriteLine("{0:C} (Celsius) = {0:K} (Kelvin) = {0:F} (Fahrenheit)", temp1)
      Console.WriteLine()
      
      ' 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)", temp1))
      Console.WriteLine()
      
      ' Call ToString method with format string.
      temp1 = New Temperature(32)
      Console.WriteLine("{0} (Celsius) = {1} (Kelvin) = {2} (Fahrenheit)", _
                        temp1.ToString("C"), temp1.ToString("K"), temp1.ToString("F"))
      Console.WriteLine()

      ' Call ToString with format string and format provider
      temp1 = New Temperature(100)      
      Dim current As NumberFormatInfo = NumberFormatInfo.CurrentInfo
      Dim nl As 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))
   End Sub
End Module
' 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)

備註

IFormattable介面會根據格式字串和格式提供者, 將物件轉換成其字串表示。The IFormattable interface converts an object to its string representation based on a format string and a format provider.

格式字串通常會定義物件的一般外觀。A format string typically defines the general appearance of an object. 例如, .NET Framework 支援下列各項:For example, the .NET Framework supports the following:

您也可以定義自己的格式字串, 以支援應用程式定義類型的格式設定。You can also define your own format strings to support formatting of your application-defined types.

格式提供者會傳回格式物件, 通常會定義用來將物件轉換為其字串表示的符號。A format provider returns a formatting object that typically defines the symbols used in converting an object to its string representation. 例如, 當您將數位轉換成貨幣值時, 格式提供者會定義出現在結果字串中的貨幣符號。For example, when you convert a number to a currency value, a format provider defines the currency symbol that appears in the result string. .NET Framework 會定義三個格式提供者:The .NET Framework defines three format providers:

此外, 您還可以定義自己的自訂格式提供者, 以提供用於格式化的特定文化特性、特定專業或業界特定的資訊。In addition, you can define your own custom format providers to supply culture-specific, profession-specific, or industry-specific information used in formatting. 如需使用自訂格式提供者來執行自訂格式的詳細ICustomFormatter資訊, 請參閱。For more information about implementing custom formatting by using a custom format provider, see ICustomFormatter.

介面會定義單一方法, ToString它會為實類型提供格式化服務。 IFormattableThe IFormattable interface defines a single method, ToString, that supplies formatting services for the implementing type. ToString方法可以直接呼叫。The ToString method can be called directly. 此外, 它是由Convert.ToString(Object)Convert.ToString(Object, IFormatProvider)方法自動呼叫, 而方法則是使用 .NET Framework 中的複合格式功能In addition, it is 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. 這類方法Console.WriteLine(String, Object)包括String.Format、和StringBuilder.AppendFormat(String, Object), 還有其他。Such methods include Console.WriteLine(String, Object), String.Format, and StringBuilder.AppendFormat(String, Object), among others. ToString方法會針對方法的格式字串中的每個格式專案呼叫。The ToString method is called for each format item in the method's format string.

IFormattable介面是由基底資料類型所執行。The IFormattable interface is implemented by the base data types.

給實施者的注意事項

需要對比ToString()提供的字串格式更有更多控制的類別IFormattable應該會執行。Classes that require more control over the formatting of strings than ToString() provides should implement IFormattable.

Implements IFormattable的類別必須支援 "G" (一般) 格式規範。A class that implements IFormattable 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

方法

ToString(String, IFormatProvider) ToString(String, IFormatProvider) ToString(String, IFormatProvider) ToString(String, IFormatProvider)

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

適用於

另請參閱