IFormatProvider Interfejs

Definicja

Udostępnia mechanizm pobierania obiektu w celu kontrolowania formatowania.

public interface class IFormatProvider
public interface IFormatProvider
[System.Runtime.InteropServices.ComVisible(true)]
public interface IFormatProvider
type IFormatProvider = interface
[<System.Runtime.InteropServices.ComVisible(true)>]
type IFormatProvider = interface
Public Interface IFormatProvider
Pochodne
Atrybuty

Przykłady

W poniższym przykładzie pokazano, jak implementacja IFormatProvider może zmienić reprezentację wartości daty i godziny. W takim przypadku pojedyncza data jest wyświetlana przy użyciu CultureInfo obiektów reprezentujących cztery różne kultury.

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
open System
open System.Globalization

let dateValue = DateTime(2009, 6, 1, 16, 37, 0)
let cultures = 
    [ CultureInfo "en-US"
      CultureInfo "fr-FR"
      CultureInfo "it-IT"
      CultureInfo "de-DE" ]

for culture in cultures do
    printfn $"{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
Imports System.Globalization

Module Example
   Public Sub Main()
      Dim dateValue As Date = #06/01/2009 4:37PM#
      Dim cultures() As CultureInfo = {New CultureInfo("en-US"), _
                                       New CultureInfo("fr-FR"), _
                                       New CultureInfo("it-IT"), _
                                       New CultureInfo("de-DE") }
      For Each culture As CultureInfo In cultures
         Console.WriteLine("{0}: {1}", culture.Name, dateValue.ToString(culture))
      Next                                        
   End Sub
End Module
' 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

Poniższy przykład ilustruje użycie klasy, która implementuje IFormatProvider interfejs i metodę GetFormat . Klasa AcctNumberFormat konwertuje Int64 wartość reprezentującą numer konta na sformatowany 12-cyfrowy numer konta. Metoda GetFormat zwraca odwołanie do bieżącego AcctNumberFormat wystąpienia, jeśli formatType parametr odwołuje się do klasy implementujące ICustomFormatter; w przeciwnym razie GetFormat zwraca wartość 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;
   }
}
open System
open System.Globalization

type AcctNumberFormat() =
    let [<Literal>] ACCT_LENGTH = 12

    interface IFormatProvider with
        member this.GetFormat(formatType: Type) =
            if formatType = typeof<ICustomFormatter> then
                this
            else
                null

    interface ICustomFormatter with
        member this.Format(fmt: string, arg: obj, formatProvider: IFormatProvider) =
            // Provide default formatting if arg is not an Int64.
            // Provide default formatting for unsupported format strings.
            let ufmt = fmt.ToUpper CultureInfo.InvariantCulture
            if arg.GetType() = typeof<Int64> && (ufmt = "H" || ufmt = "I") then
                // Convert argument to a string.
                let result = string arg

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

                // Integer-only format.
                if ufmt = "I" then 
                    result
                // Add hyphens for H format specifier.
                else // Hyphenated format.
                    result.Substring(0, 5) + "-" + result.Substring(5, 3) + "-" + result.Substring(8)
            else
                try
                    this.HandleOtherFormats(fmt, arg)
                with :? FormatException as e ->
                    raise (FormatException($"The format of '{fmt}' is invalid.", e))
            
    member _.HandleOtherFormats(format: string, arg: obj) =
        match arg with
        | :? IFormattable as arg ->
            arg.ToString(format, CultureInfo.CurrentCulture)
        | null -> 
            string arg
        | _ -> 
            String.Empty
Public Class AcctNumberFormat : Implements IFormatProvider, ICustomFormatter

   Private Const ACCT_LENGTH As Integer = 12
   
   Public Function GetFormat(formatType As Type) As Object _
                   Implements IFormatProvider.GetFormat
      If formatType Is GetType(ICustomFormatter) Then
         Return Me
      Else
         Return Nothing
      End If
   End Function
   
   Public Function Format(fmt As String, arg As Object, formatProvider As IFormatProvider) As String _
                          Implements ICustomFormatter.Format

      ' Provide default formatting if arg is not an Int64.
       If Not TypeOf arg Is Int64 Then
         Try 
            Return HandleOtherFormats(fmt, arg) 
         Catch e As FormatException 
            Throw New FormatException(String.Format("The format of '{0}' is invalid.", fmt), e)
         End Try
       End If   
                     
      ' Provider default formatting for unsupported format strings.
      Dim ufmt As String = fmt.ToUpper(CultureInfo.InvariantCulture)
      If Not (ufmt = "H" Or ufmt = "I") Then
         Try
            Return HandleOtherFormats(fmt, arg)
         Catch e As FormatException 
            Throw New FormatException(String.Format("The format of '{0}' is invalid.", fmt), e)
         End Try
      End If   

      ' Convert argument to a string.
      Dim result As String = arg.ToString()
      
      ' If account number is less than 12 characters, pad with leading zeroes.
      If result.Length < ACCT_LENGTH Then result = result.PadLeft(ACCT_LENGTH, "0"c)
      ' If account number is more than 12 characters, truncate to 12 characters.
      If result.Length > ACCT_LENGTH Then result = Left(result, ACCT_LENGTH)   
      
      If ufmt = "I"                              ' Integer-only format.
         Return result
      ' Add hyphens for H format specifier.
      Else                                       ' Hypenated format.
         Return Left(result, 5) & "-" & Mid(result, 6, 3) & "-" & Right(result, 4)
      End If   
   End Function   

   Private Function HandleOtherFormats(fmt As String, arg As Object) As String
      If TypeOf arg Is IFormattable Then
         Return DirectCast(arg, IFormattable).ToString(fmt, CultureInfo.CurrentCulture)
      ElseIf arg IsNot Nothing Then
         Return arg.ToString()
      Else
         Return String.Empty
      End If
   End Function
End Class

Klasa, która implementuje IFormatProvider , może być następnie używana w wywołaniu operacji formatowania i analizowania. Na przykład poniższy kod wywołuje metodę String.Format(IFormatProvider, String, Object[]) w celu wygenerowania ciągu zawierającego sformatowany 12-cyfrowy numer konta.

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.
open System
open System.Globalization

type DaysOfWeek = Monday = 1 | Tuesday = 2

[<EntryPoint>]
let main _ =
    let acctNumber = 104254567890L
    let balance = 16.34
    let wday = DaysOfWeek.Monday

    let output = 
        String.Format(AcctNumberFormat(), 
                      "On {2}, the balance of account {0:H} was {1:C2}.", 
                      acctNumber, balance, wday)
    printfn $"{output}"

    let wday = DaysOfWeek.Tuesday
    let output = 
        String.Format(AcctNumberFormat(),
                      "On {2}, the balance of account {0:I} was {1:C2}.",
                      acctNumber, balance, wday)
    printfn $"{output}"
    0

// 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.
Imports System.Globalization

Public Enum DaysOfWeek As Long
   Monday = 1
   Tuesday = 2
End Enum

Module TestFormatting
   Public Sub Main()
      Dim acctNumber As Long, balance As Double 
      Dim wday As DaysOfWeek 
      Dim output As String

      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)
   End Sub
End Module
' 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.

Uwagi

Interfejs IFormatProvider dostarcza obiekt, który udostępnia informacje o formatowaniu operacji formatowania i analizowania. Operacje formatowania konwertują wartość typu na reprezentację ciągu tej wartości. Typowe metody formatowania to ToString metody typu, a także Format. Operacje analizowania konwertują reprezentację ciągu wartości na typ z tej wartości. Typowe metody analizowania to Parse i TryParse.

Interfejs IFormatProvider składa się z jednej metody : IFormatProvider.GetFormat. GetFormat to metoda wywołania zwrotnego: metoda analizowania lub formatowania wywołuje ją i przekazuje do niego Type obiekt reprezentujący typ obiektu, którego oczekuje metoda formatowania lub analizowania, zapewni informacje o formatowaniu. Metoda GetFormat jest odpowiedzialna za zwracanie obiektu tego typu.

IFormatProvider implementacje są często używane niejawnie przez metody formatowania i analizowania. Na przykład DateTime.ToString(String) metoda niejawnie używa IFormatProvider implementacji reprezentującej bieżącą kulturę systemu. IFormatProvider Implementacje można również określić jawnie za pomocą metod, które mają parametr typu IFormatProvider, na przykład Int32.Parse(String, IFormatProvider) i String.Format(IFormatProvider, String, Object[]).

.NET Framework zawiera następujące trzy wstępnie zdefiniowane IFormatProvider implementacje, które zapewniają informacje specyficzne dla kultury, które są używane do formatowania lub analizowania wartości liczbowych i daty i godziny:

.NET Framework obsługuje również formatowanie niestandardowe. Zwykle obejmuje to utworzenie klasy formatowania, która implementuje zarówno klasy , jak IFormatProvider i ICustomFormatter. Wystąpienie tej klasy jest następnie przekazywane jako parametr do metody wykonującej niestandardową operację formatowania, na String.Format(IFormatProvider, String, Object[]) przykład przykładzie przedstawiono taką niestandardową implementację, która formatuje liczbę jako 12-cyfrowy numer konta.

Metody

GetFormat(Type)

Zwraca obiekt, który udostępnia usługi formatowania dla określonego typu.

Dotyczy

Zobacz też