IFormatProvider 接口

定义

提供一种机制,用于检索对象以控制格式化。

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
派生
属性

示例

下面的示例演示了实现如何 IFormatProvider 更改日期和时间值的表示形式。 在这种情况下,使用 CultureInfo 表示四种不同区域性的对象显示单个日期。

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

下面的示例演示了实现 IFormatProvider 接口和方法的类的使用 GetFormat 。 该 AcctNumberFormat 类将表示 Int64 帐户号的值转换为带格式的 12 位帐户号。 如果参数引用实现的类,则其GetFormat方法返回对当前AcctNumberFormat实例的ICustomFormatter引用;否则GetFormat返回nullformatType

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

然后,可以在调用格式和分析操作时使用实现 IFormatProvider 的类。 例如,以下代码调用 String.Format(IFormatProvider, String, Object[]) 该方法以生成包含带格式的 12 位帐户号的字符串。

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.

注解

IFormatProvider 接口提供一个对象,该对象提供格式设置和分析操作的格式信息。 格式设置操作将类型的值转换为该值的字符串表示形式。 典型的格式设置方法是 ToString 类型的方法,以及 Format。 分析操作将值的字符串表示形式转换为具有该值的类型。 典型的分析方法是 ParseTryParse

接口IFormatProvider由单个方法组成。 IFormatProvider.GetFormat GetFormat 是回调方法:分析或格式化方法调用它并传递一个 Type 对象,该对象表示格式设置或分析方法期望的对象类型将提供格式设置信息。 该方法 GetFormat 负责返回该类型的对象。

IFormatProvider 实现通常通过格式化和分析方法隐式使用。 例如,该方法 DateTime.ToString(String) 隐式使用 IFormatProvider 表示系统当前区域性的实现。 IFormatProvider 还可以通过具有类型 IFormatProvider参数的方法(如 Int32.Parse(String, IFormatProvider)String.Format(IFormatProvider, String, Object[]))显式指定实现。

.NET Framework包括以下三个预定义IFormatProvider实现,以提供用于设置或分析数值和日期和时间值的格式设置或分析区域性特定的信息:

.NET Framework还支持自定义格式设置。 这通常涉及创建实现这两种格式 IFormatProviderICustomFormatter格式设置类。 然后,此类的实例作为参数传递给执行自定义格式设置操作的方法,例如 String.Format(IFormatProvider, String, Object[]) ,该示例提供了一个将数字格式化为 12 位帐户号的自定义实现的插图。

方法

GetFormat(Type)

返回一个对象,该对象为指定类型提供格式设置服务。

适用于

另请参阅