IFormatProvider 接口

定义

提供一种机制,用于检索对象以控制格式化。Provides a mechanism for retrieving an object to control formatting.

public interface class IFormatProvider
public interface IFormatProvider
[System.Runtime.InteropServices.ComVisible(true)]
public interface IFormatProvider
type IFormatProvider = interface
Public Interface IFormatProvider
派生
属性

示例

下面的示例演示了 IFormatProvider 实现如何更改日期和时间值的表示形式。The following example illustrates how an IFormatProvider implementation can change the representation of a date and time value. 在这种情况下,将使用表示四个不同区域性 CultureInfo 对象显示单个日期。In this case, a single date is displayed by using 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, 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
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 方法的类。The following example illustrates the use of a class that implements the IFormatProvider interface and the GetFormat method. AcctNumberFormat 类将表示帐号的 Int64 值转换为格式化的12位数帐号。The AcctNumberFormat class converts an Int64 value that represents an account number to a formatted 12-digit account number. 如果 formatType 参数引用实现 ICustomFormatter的类,则其 GetFormat 方法返回对当前 AcctNumberFormat 实例的引用;否则,GetFormat 返回 nullIts GetFormat method returns a reference to the current AcctNumberFormat instance if the formatType parameter refers to a class that implements 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;
   }
}
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 的类。The class that implements IFormatProvider can then be used in a call to a formatting and parsing operation. 例如,下面的代码调用 String.Format(IFormatProvider, String, Object[]) 方法来生成一个字符串,该字符串包含带格式的12位数帐号。For example, the following code calls the String.Format(IFormatProvider, String, 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.
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 接口提供一个对象,该对象提供格式设置信息以进行格式设置和分析操作。The 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. 典型格式设置方法是类型的 ToString 方法以及 FormatTypical formatting methods are the ToString methods of a type, as well as Format. 分析操作将值的字符串表示形式转换为具有该值的类型。Parsing operations convert the string representation of a value to a type with that value. 典型的分析方法 ParseTryParseTypical parsing methods are Parse and TryParse.

IFormatProvider 接口包含一个方法,IFormatProvider.GetFormatThe IFormatProvider interface consists of a single method, IFormatProvider.GetFormat. GetFormat 是回调方法:分析或格式设置方法会调用它,并向其传递一个表示格式设置或分析方法预期的对象类型的 Type 对象将提供格式设置信息。GetFormat is a callback method: The parsing or formatting method calls it and passes it a Type object that represents the type of object that the formatting or parsing method expects will provide formatting information. GetFormat 方法负责返回该类型的对象。The GetFormat method is responsible for returning an object of that type.

IFormatProvider 实现通常通过格式设置和分析方法隐式使用。IFormatProvider implementations are often used implicitly by formatting and parsing methods. 例如,DateTime.ToString(String) 方法隐式使用表示系统当前区域性的 IFormatProvider 实现。For example, the DateTime.ToString(String) method implicitly uses an IFormatProvider implementation that represents the system's current culture. 还可以通过具有类型 IFormatProvider的参数的方法(如 Int32.Parse(String, IFormatProvider)String.Format(IFormatProvider, String, Object[]))显式指定 IFormatProvider 实现。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[]).

.NET Framework 包含以下三个预定义的 IFormatProvider 实现,以提供用于对数字和日期和时间值进行格式设置或分析的区域性特定信息:The .NET Framework includes the following three predefined IFormatProvider implementations to provide culture-specific information that is used in formatting or parsing numeric and date and time values:

.NET Framework 还支持自定义格式设置。The .NET Framework also supports custom formatting. 这通常涉及创建同时实现 IFormatProviderICustomFormatter的格式设置类。This typically involves the creation of a formatting class that implements both IFormatProvider and ICustomFormatter. 然后,将此类的一个实例作为参数传递给执行自定义格式设置操作的方法,例如 String.Format(IFormatProvider, String, Object[]) 此示例提供了一个将数字设置为12位数帐号的自定义实现的插图。An instance of this class is then passed as a parameter to a method that performs a custom formatting operation, such as String.Format(IFormatProvider, String, Object[]) The example provides an illustration of such a custom implementation that formats a number as a 12-digit account number.

方法

GetFormat(Type)

返回一个对象,该对象为指定类型提供格式设置服务。Returns an object that provides formatting services for the specified type.

适用于

另请参阅