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 IFormatProvider

 

Fornece um mecanismo para recuperar um objeto para controlar a formatação.

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

[ComVisibleAttribute(true)]
public interface IFormatProvider

NomeDescrição
System_CAPS_pubmethodGetFormat(Type)

Retorna um objeto que fornece serviços de formatação para o tipo especificado.

The T:System.IFormatProvider interface supplies an object that provides formatting information for formatting and parsing operations. Formatting operations convert the value of a type to the string representation of that value. Typical formatting methods are the ToString methods of a type, as well as M:System.String.Format(System.String,System.Object). Parsing operations convert the string representation of a value to a type with that value. Typical parsing methods are Parse and TryParse.

The T:System.IFormatProvider interface consists of a single method, M:System.IFormatProvider.GetFormat(System.Type). M:System.IFormatProvider.GetFormat(System.Type) is a callback method: The parsing or formatting method calls it and passes it a T:System.Type object that represents the type of object that the formatting or parsing method expects will provide formatting information. The M:System.IFormatProvider.GetFormat(System.Type) method is responsible for returning an object of that type.

IFormatProvider implementations are often used implicitly by formatting and parsing methods. For example, the DateTime.ToString(String) method implicitly uses an IFormatProvider implementation that represents the system's current culture. IFormatProvider implementations can also be specified explicitly by methods that have a parameter of type IFormatProvider, such as Int32.Parse(String, IFormatProvider) and String.Format(IFormatProvider, String, Object[]).

The .NET Framework includes the following three predefined T:System.IFormatProvider implementations to provide culture-specific information that is used in formatting or parsing numeric and date and time values:

  • The T:System.Globalization.NumberFormatInfo class, which provides information that is used to format numbers, such as the currency, thousands separator, and decimal separator symbols for a particular culture. For information about the predefined format strings recognized by a T:System.Globalization.NumberFormatInfo object and used in numeric formatting operations, see Standard Numeric Format Strings and Custom Numeric Format Strings.

  • The T:System.Globalization.DateTimeFormatInfo class, which provides information that is used to format dates and times, such as the date and time separator symbols for a particular culture or the order and format of a date's year, month, and day components. For information about the predefined format strings recognized by a T:System.Globalization.DateTimeFormatInfo object and used in numeric formatting operations, see Standard Date and Time Format Strings and Custom Date and Time Format Strings.

  • The T:System.Globalization.CultureInfo class, which represents a particular culture. Its M:System.IFormatProvider.GetFormat(System.Type) method returns a culture-specific T:System.Globalization.NumberFormatInfo or T:System.Globalization.DateTimeFormatInfo object, depending on whether the T:System.Globalization.CultureInfo object is used in a formatting or parsing operation that involves numbers or dates and times.

The .NET Framework also supports custom formatting. This typically involves the creation of a formatting class that implements both T:System.IFormatProvider and T:System.ICustomFormatter. An instance of this class is then passed as a parameter to a method that performs a custom formatting operation, such as M:System.String.Format(System.IFormatProvider,System.String,System.Object[]) The example provides an illustration of such a custom implementation that formats a number as a 12-digit account number.

The following example illustrates how an T:System.IFormatProvider implementation can change the representation of a date and time value. In this case, a single date is displayed by using T:System.Globalization.CultureInfo objects that represent four different cultures.

using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      DateTime dateValue = new DateTime(2009, 6, 1, 4, 37, 0);
      CultureInfo[] cultures = { new CultureInfo("en-US"), 
                                 new CultureInfo("fr-FR"),
                                 new CultureInfo("it-IT"),
                                 new CultureInfo("de-DE") };
      foreach (CultureInfo culture in cultures)
         Console.WriteLine("{0}: {1}", culture.Name, dateValue.ToString(culture));
   }
}
// The example displays the following output:
//       en-US: 6/1/2009 4:37:00 PM
//       fr-FR: 01/06/2009 16:37:00
//       it-IT: 01/06/2009 16.37.00
//       de-DE: 01.06.2009 16:37:00

The following example illustrates the use of a class that implements the T:System.IFormatProvider interface and the M:System.IFormatProvider.GetFormat(System.Type) method. The AcctNumberFormat class converts an T:System.Int64 value that represents an account number to a formatted 12-digit account number. Its GetFormat method returns a reference to the current AcctNumberFormat instance if the formatType parameter refers to a class that implements T:System.ICustomFormatter; otherwise, GetFormat returns null.

public class AcctNumberFormat : IFormatProvider, ICustomFormatter
{
   private const int ACCT_LENGTH = 12;

   public object GetFormat(Type formatType)
   {
      if (formatType == typeof(ICustomFormatter))
         return this;
      else
         return null;
   }

   public string Format(string fmt, object arg, IFormatProvider formatProvider) 
   {
      // Provide default formatting if arg is not an Int64.
      if (arg.GetType() != typeof(Int64))
         try {
            return HandleOtherFormats(fmt, arg); 
         }
         catch (FormatException e) {
            throw new FormatException(String.Format("The format of '{0}' is invalid.", fmt), e);
         }

      // Provide default formatting for unsupported format strings.
      string ufmt = fmt.ToUpper(CultureInfo.InvariantCulture);
      if (! (ufmt == "H" || ufmt == "I")) 
         try {
            return HandleOtherFormats(fmt, arg);
         }
         catch (FormatException e) {
            throw new FormatException(String.Format("The format of '{0}' is invalid.", fmt), e);
         }

      // Convert argument to a string.
      string result = arg.ToString();

      // If account number is less than 12 characters, pad with leading zeroes.
      if (result.Length < ACCT_LENGTH)
         result = result.PadLeft(ACCT_LENGTH, '0');
      // If account number is more than 12 characters, truncate to 12 characters.
      if (result.Length > ACCT_LENGTH)
         result = result.Substring(0, ACCT_LENGTH);   

      if (ufmt == "I")                    // Integer-only format. 
         return result;
      // Add hyphens for H format specifier.
      else                                         // Hyphenated format.
         return result.Substring(0, 5) + "-" + result.Substring(5, 3) + "-" + result.Substring(8);
   }

   private string HandleOtherFormats(string format, object arg)
   {
      if (arg is IFormattable) 
         return ((IFormattable)arg).ToString(format, CultureInfo.CurrentCulture);
      else if (arg != null)
         return arg.ToString();
      else
         return String.Empty;
   }
}

The class that implements T:System.IFormatProvider can then be used in a call to a formatting and parsing operation. For example, the following code calls the M:System.String.Format(System.IFormatProvider,System.String,System.Object[]) method to generate a string that contains a formatted 12-digit account number.

using System;
using System.Globalization;

public enum DaysOfWeek { Monday=1, Tuesday=2 };

public class TestFormatting
{
   public static void Main()
   {
      long acctNumber;
      double balance; 
      DaysOfWeek wday; 
      string output;

      acctNumber = 104254567890;
      balance = 16.34;
      wday = DaysOfWeek.Monday;

      output = String.Format(new AcctNumberFormat(), 
                             "On {2}, the balance of account {0:H} was {1:C2}.", 
                             acctNumber, balance, wday);
      Console.WriteLine(output);

      wday = DaysOfWeek.Tuesday;
      output = String.Format(new AcctNumberFormat(), 
                             "On {2}, the balance of account {0:I} was {1:C2}.", 
                             acctNumber, balance, wday);
      Console.WriteLine(output);
   }
}
// The example displays the following output:
//       On Monday, the balance of account 10425-456-7890 was $16.34.
//       On Tuesday, the balance of account 104254567890 was $16.34.

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: