IFormattable 接口

定义

提供一种功能,用以将对象的值格式化为字符串表示形式。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. 可以直接调用方法。 ToStringThe 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. 为方法的格式字符串中的每个格式项调用方法。ToStringThe 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()格式的类应实现。 IFormattableClasses that require more control over the formatting of strings than ToString() provides should implement IFormattable.

实现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)

使用指定的格式格式化当前实例的值。Formats the value of the current instance using the specified format.

适用于

另请参阅