Leggere in inglese

Condividi tramite


IFormatProvider Interfaccia

Definizione

Fornisce un meccanismo per il recupero di un oggetto allo scopo di controllare la formattazione.

C#
public interface IFormatProvider
C#
[System.Runtime.InteropServices.ComVisible(true)]
public interface IFormatProvider
Derivato
Attributi

Esempio

Nell'esempio seguente viene illustrato come un'implementazione IFormatProvider può modificare la rappresentazione di un valore di data e ora. In questo caso, viene visualizzata una singola data usando CultureInfo oggetti che rappresentano quattro impostazioni cultura diverse.

C#
using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      DateTime dateValue = new DateTime(2009, 6, 1, 16, 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

Nell'esempio seguente viene illustrato l'uso di una classe che implementa l'interfaccia IFormatProvider e il GetFormat metodo . La AcctNumberFormat classe converte un Int64 valore che rappresenta un numero di conto in un numero di conto formattato a 12 cifre. Il GetFormat metodo restituisce un riferimento all'istanza corrente AcctNumberFormat se il formatType parametro fa riferimento a una classe che implementa ICustomFormatter; in caso contrario, GetFormat restituisce null.

C#
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;
   }
}

La classe che implementa IFormatProvider può quindi essere usata in una chiamata a un'operazione di formattazione e analisi. Ad esempio, il codice seguente chiama il String.Format(IFormatProvider, String, Object[]) metodo per generare una stringa contenente un numero di conto di 12 cifre formattato.

C#
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.

Commenti

L'interfaccia IFormatProvider fornisce un oggetto che fornisce informazioni di formattazione per operazioni di formattazione e analisi. Le operazioni di formattazione converteno il valore di un tipo nella rappresentazione di stringa di tale valore. I metodi di formattazione tipici sono i ToString metodi di un tipo, nonché Format. Le operazioni di analisi converte la rappresentazione di stringa di un valore in un tipo con tale valore. I metodi di analisi tipici sono Parse e TryParse.

L'interfaccia IFormatProvider è costituita da un singolo metodo, IFormatProvider.GetFormat. GetFormat è un metodo di callback: il metodo di analisi o formattazione lo chiama e lo passa a un Type oggetto che rappresenta il tipo di oggetto previsto dal metodo di formattazione o analisi. Il GetFormat metodo è responsabile della restituzione di un oggetto di tale tipo.

IFormatProvider le implementazioni vengono spesso usate in modo implicito tramite la formattazione e l'analisi dei metodi. Ad esempio, il DateTime.ToString(String) metodo usa in modo implicito un'implementazione IFormatProvider che rappresenta le impostazioni cultura correnti del sistema. IFormatProvider Le implementazioni possono anche essere specificate in modo esplicito dai metodi che hanno un parametro di tipo IFormatProvider, ad esempio Int32.Parse(String, IFormatProvider) e String.Format(IFormatProvider, String, Object[]).

Il .NET Framework include le tre implementazioni predefinite IFormatProvider seguenti per fornire informazioni specifiche delle impostazioni cultura usate nella formattazione o nell'analisi dei valori numerici e di data e ora:

Il .NET Framework supporta anche la formattazione personalizzata. Ciò comporta in genere la creazione di una classe di formattazione che implementa sia che IFormatProvider ICustomFormatter. Un'istanza di questa classe viene quindi passata come parametro a un metodo che esegue un'operazione di formattazione personalizzata, ad esempio String.Format(IFormatProvider, String, Object[]) L'esempio fornisce un'illustrazione di tale implementazione personalizzata che formatta un numero come numero di conto a 12 cifre.

Metodi

GetFormat(Type)

Restituisce un oggetto che fornisce servizi di formattazione per il tipo specificato.

Si applica a

Prodotto Versioni
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

Vedi anche