IFormatProvider 接口

定义

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

C#
public interface IFormatProvider
C#
[System.Runtime.InteropServices.ComVisible(true)]
public interface IFormatProvider
派生
属性

示例

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

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

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

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

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

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.

注解

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)

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

适用于

产品 版本
.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

另请参阅