英語で読む

次の方法で共有


IFormatProvider インターフェイス

定義

書式設定を制御するオブジェクトを取得するためのメカニズムを定義します。

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

次の例は、実装によって IFormatProvider 日付と時刻の値の表現を変更する方法を示しています。 この場合、4 つの異なるカルチャを表すオブジェクトを使用して CultureInfo 、1 つの日付が表示されます。

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

次の例は、インターフェイスとメソッドを実装するクラスの使用をIFormatProviderGetFormat示しています。 このクラスは AcctNumberFormat 、アカウント番号を Int64 表す値を書式設定された 12 桁のアカウント番号に変換します。 パラメーターが実装するクラスを参照している場合、そのGetFormatメソッドは現在AcctNumberFormatformatTypeインスタンスへの参照を返します。それ以外のnull場合は、 GetFormat .ICustomFormatter

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同様です。 解析操作は、値の文字列表現を、その値を持つ型に変換します。 一般的な解析方法は Parse 次のとおりです TryParse

インターフェイスは IFormatProviderIFormatProvider.GetFormat1 つのメソッドで構成されます。 GetFormat はコールバック メソッドです。解析メソッドまたは書式設定メソッドは、それを呼び出し、書式設定または解析メソッドが書式設定情報を提供するオブジェクトの種類を表すオブジェクトを渡 Type します。 メソッドは GetFormat 、その型のオブジェクトを返す役割を担います。

IFormatProvider 実装は、多くの場合、メソッドの書式設定と解析によって暗黙的に使用されます。 たとえば、メソッドは、システムの DateTime.ToString(String) 現在のカルチャを IFormatProvider 表す実装を暗黙的に使用します。 IFormatProvider実装は、次のようなInt32.Parse(String, IFormatProvider)String.Format(IFormatProvider, String, Object[])IFormatProviderのパラメーターを持つメソッドによって明示的に指定することもできます。

.NET Frameworkには、数値と日付と時刻の値の書式設定または解析に使用されるカルチャ固有の情報を提供するために、次の 3 つの定義済みのIFormatProvider実装が含まれています。

.NET Frameworkでは、カスタム書式設定もサポートされています。 これには通常、両方 IFormatProvider を実装する書式設定クラスの作成が ICustomFormatter含まれます。 このクラスのインスタンスは、カスタム書式設定操作を実行するメソッドにパラメーターとして渡されます。たとえば 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

こちらもご覧ください