Condividi tramite


IFormattable Interface

Microsoft Silverlight will reach end of support after October 2021. Learn more.

Provides functionality to format the value of an object into a string representation.

Namespace:  System
Assembly:  mscorlib (in mscorlib.dll)

Syntax

'Declaration
<ComVisibleAttribute(True)> _
Public Interface IFormattable
[ComVisibleAttribute(true)]
public interface IFormattable

The IFormattable type exposes the following members.

Methods

  Name Description
Public methodSupported by Silverlight for Windows PhoneSupported by Xbox 360 ToString Formats the value of the current instance using the specified format.

Top

Remarks

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. 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. 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. For more information about implementing custom formatting by using a custom format provider, see ICustomFormatter.

The IFormattable interface defines a single method, ToString, that supplies formatting services for the implementing type. The ToString method can be called directly. 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. Such methods include String.Format and StringBuilder.AppendFormat, among others. The ToString method is called for each format item in the method's format string.

IFormattable is implemented by the base data types.

Notes to Implementers

Classes that require more control over the formatting of strings than Object.ToString provides should implement IFormattable.

A class that implements IFormattable must support the "G" (general) formatting code. Besides the "G" code, the class can define the list of formatting codes that it supports. In addition, the class must be prepared to handle a format specifier that is nulla null reference (Nothing in Visual Basic). For more information on formatting and formatting codes, see Formatting Types.

Examples

The following example defines a Temperature class that implements the IFormattable interface. 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. In addition, the IFormattable.ToString implementation also can handle a format string that is nulla null reference (Nothing in Visual Basic) or empty. The other two ToString methods defined by the Temperature class simply wrap a call to the IFormattable.ToString implementation.

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

The following example then calls the IFormattable.ToString implementation either directly or by using a composite format string.

Module Example
   Public Sub Demo(outputBlock As System.Windows.Controls.TextBlock)
      ' Use composite formatting with format string in the format item.
      Dim temp1 As New Temperature(0)
      outputBlock.Text += String.Format("{0:C} (Celsius) = {0:K} (Kelvin) = {0:F} (Fahrenheit)", temp1) 
      outputBlock.Text += vbCrLf

      ' Use composite formatting with a format provider.
      temp1 = New Temperature(-40)
      outputBlock.Text += String.Format(CultureInfo.CurrentCulture, "{0:C} (Celsius) = {0:K} (Kelvin) = {0:F} (Fahrenheit)", temp1)
      outputBlock.Text += vbCrLf
      outputBlock.Text += String.Format(New CultureInfo("fr-FR"), "{0:C} (Celsius) = {0:K} (Kelvin) = {0:F} (Fahrenheit)", temp1)
      outputBlock.Text += vbCrLf

      ' Call ToString method with format string.
      temp1 = New Temperature(32)
      outputBlock.Text += String.Format("{0} (Celsius) = {1} (Kelvin) = {2} (Fahrenheit)", _
                                        temp1.ToString("C"), temp1.ToString("K"), temp1.ToString("F"))
      outputBlock.Text += vbCrLf

      ' 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") 
      outputBlock.Text += String.Format("{0} (Celsius) = {1} (Kelvin) = {2} (Fahrenheit)", _
                        temp1.ToString("C", current), temp1.ToString("K", current), temp1.ToString("F", current))
      outputBlock.Text += vbCrLf
      outputBlock.Text += String.Format("{0} (Celsius) = {1} (Kelvin) = {2} (Fahrenheit)", _
                        temp1.ToString("C", nl), temp1.ToString("K", nl), temp1.ToString("F", nl))
      outputBlock.Text += vbCrLf
   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)
public class Example
{
   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {
      // Use composite formatting with format string in the format item.
      Temperature temp1 = new Temperature(0);
      outputBlock.Text += String.Format("{0:C} (Celsius) = {0:K} (Kelvin) = {0:F} (Fahrenheit)\n", temp1);

      // Use composite formatting with a format provider.
      temp1 = new Temperature(-40);
      outputBlock.Text += String.Format(CultureInfo.CurrentCulture, "{0:C} (Celsius) = {0:K} (Kelvin) = {0:F} (Fahrenheit)\n", temp1);
      outputBlock.Text += 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);
      outputBlock.Text += String.Format("{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"); 
      outputBlock.Text += String.Format("{0} (Celsius) = {1} (Kelvin) = {2} (Fahrenheit)\n", 
                        temp1.ToString("C", current), temp1.ToString("K", current), temp1.ToString("F", current));
      outputBlock.Text += String.Format("{0} (Celsius) = {1} (Kelvin) = {2} (Fahrenheit)\n", 
                        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)

Version Information

Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0

XNA Framework

Supported in: Xbox 360, Windows Phone OS 7.0

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.