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",指示要在中 Kelvin 显示温度。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. 其他两个ToString定义的方法Temperature类只包装调用IFormattable.ToString实现。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. 有关实现通过使用自定义格式提供程序自定义格式设置的详细信息,请参阅ICustomFormatterFor more information about implementing custom formatting by using a custom format provider, see ICustomFormatter.

IFormattable接口定义一个方法, ToString,,它提供的实现类型的格式设置服务。The 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()提供了应实现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) ToString(String, IFormatProvider) ToString(String, IFormatProvider) ToString(String, IFormatProvider)

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

适用于

另请参阅