Este artigo foi traduzido por máquina. Para visualizar o arquivo em inglês, marque a caixa de seleção Inglês. Você também pode exibir o texto Em inglês em uma janela pop-up, movendo o ponteiro do mouse sobre o texto.
Tradução
Inglês

Interface IFormattable

 

Fornece funcionalidade para formatar o valor de um objeto em uma representação de cadeia de caracteres.

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

[ComVisibleAttribute(true)]
public interface IFormattable

NomeDescrição
System_CAPS_pubmethodToString(String, IFormatProvider)

Formata o valor da instância atual usando o formato especificado.

The T:System.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:

  • Standard format strings for formatting enumeration values (see Enumeration Format Strings).

  • Standard and custom format strings for formatting numeric values (see Standard Numeric Format Strings and Custom Numeric Format Strings).

  • Standard and custom format strings for formatting date and time values (see Standard Date and Time Format Strings and Custom Date and Time Format Strings).

  • Standard and custom format strings for formatting time intervals (see Standard TimeSpan Format Strings and Custom TimeSpan Format Strings).

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:

  • The T:System.Globalization.CultureInfo class, which returns either a T:System.Globalization.NumberFormatInfo object for formatting numeric values, or a T:System.Globalization.DateTimeFormatInfo object for formatting date and time values.

  • The T:System.Globalization.NumberFormatInfo class, which returns an instance of itself for formatting numeric values.

  • The T:System.Globalization.DateTimeFormatInfo class, which returns an instance of itself for formatting date and time values.

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 T:System.ICustomFormatter.

The T:System.IFormattable interface defines a single method, M:System.IFormattable.ToString(System.String,System.IFormatProvider), that supplies formatting services for the implementing type. The M:System.IFormattable.ToString(System.String,System.IFormatProvider) method can be called directly. In addition, it is called automatically by the M:System.Convert.ToString(System.Object) and M:System.Convert.ToString(System.Object,System.IFormatProvider) methods, and by methods that use the composite formatting feature in the .NET Framework. Such methods include M:System.Console.WriteLine(System.String,System.Object), M:System.String.Format(System.String,System.Object[]), and M:System.Text.StringBuilder.AppendFormat(System.String,System.Object), among others. The M:System.IFormattable.ToString(System.String,System.IFormatProvider) method is called for each format item in the method's format string.

The T:System.IFormattable interface is implemented by the base data types.

Observações para os Implementadores:

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

A class that implements T:System.IFormattable must support the "G" (general) format specifier. Besides the "G" specifier, the class can define the list of format specifiers that it supports. In 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 in the .NET Framework

The following example defines a Temperature class that implements the T:System.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 M:System.IFormattable.ToString(System.String,System.IFormatProvider) implementation also can handle a format string that is null or empty. The other two ToString methods defined by the Temperature class simply wrap a call to the M:System.IFormattable.ToString(System.String,System.IFormatProvider) 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));
      }
   }
}

The following example then calls the M:System.IFormattable.ToString(System.String,System.IFormatProvider) 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)

Plataforma Universal do Windows
Disponível desde 8
.NET Framework
Disponível desde 1.1
Biblioteca de Classes Portátil
Com suporte no: plataformas portáteis do .NET
Silverlight
Disponível desde 2.0
Windows Phone Silverlight
Disponível desde 7.0
Windows Phone
Disponível desde 8.1
Retornar ao início
Mostrar: