英語で読む

次の方法で共有


ICustomFormatter.Format(String, Object, IFormatProvider) メソッド

定義

指定した形式およびカルチャ固有の書式設定情報を使用して、指定したオブジェクトの値をそれと等価の文字列形式に変換します。

C#
public string Format(string format, object arg, IFormatProvider formatProvider);
C#
public string Format(string? format, object? arg, IFormatProvider? formatProvider);

パラメーター

format
String

書式設定の仕様を含む書式文字列。

arg
Object

書式指定するオブジェクト。

formatProvider
IFormatProvider

現在のインスタンスに関する書式情報を提供するオブジェクト。

戻り値

formatformatProvider の指定のとおりに書式設定された、arg の値の文字列形式。

次の例では、 ICustomFormatter を実装して、整数値のバイナリ、8 進数、および 16 進数の書式設定を許可します。 その ICustomFormatter.Format 実装では、format パラメーターがサポートされている 3 つの書式指定文字列 (バイナリの場合は "B"、8 進数の場合は "O"、16 進数の場合は "H" のいずれか) であるかどうかを判断し、パラメーターを arg 適切に書式設定します。 それ以外の場合、 が でないnull場合argは、存在するarg場合はパラメーターのIFormattable.ToString実装を呼び出し、存在しない場合はパラメーターなしのToStringメソッドを呼び出します。 argnull の場合、メソッドは String.Empty を返します。

C#
using System;
using System.Globalization;
using System.Numerics;

public class MyFormatter : IFormatProvider, ICustomFormatter
{
    // IFormatProvider.GetFormat implementation.
    public object GetFormat(Type formatType)
    {
        // Determine whether custom formatting object is requested.
        if (formatType == typeof(ICustomFormatter))
            return this;
        else
            return null;
    }

    // Format number in binary (B), octal (O), or hexadecimal (H).
    public string Format(string format, object arg, IFormatProvider formatProvider)
    {
        // Handle format string.
        int baseNumber;
        // Handle null or empty format string, string with precision specifier.
        string thisFmt = String.Empty;
        // Extract first character of format string (precision specifiers
        // are not supported).
        if (!String.IsNullOrEmpty(format))
            thisFmt = format.Length > 1 ? format.Substring(0, 1) : format;

        // Get a byte array representing the numeric value.
        byte[] bytes;
        if (arg is sbyte)
        {
            string byteString = ((sbyte)arg).ToString("X2");
            bytes = new byte[1] { Byte.Parse(byteString, System.Globalization.NumberStyles.HexNumber) };
        }
        else if (arg is byte)
        {
            bytes = new byte[1] { (byte)arg };
        }
        else if (arg is short)
        {
            bytes = BitConverter.GetBytes((short)arg);
        }
        else if (arg is int)
        {
            bytes = BitConverter.GetBytes((int)arg);
        }
        else if (arg is long)
        {
            bytes = BitConverter.GetBytes((long)arg);
        }
        else if (arg is ushort)
        {
            bytes = BitConverter.GetBytes((ushort)arg);
        }
        else if (arg is uint)
        {
            bytes = BitConverter.GetBytes((uint)arg);
        }
        else if (arg is ulong)
        {
            bytes = BitConverter.GetBytes((ulong)arg);
        }
        else if (arg is BigInteger)
        {
            bytes = ((BigInteger)arg).ToByteArray();
        }
        else
        {
            try
            {
                return HandleOtherFormats(format, arg);
            }
            catch (FormatException e)
            {
                throw new FormatException(String.Format("The format of '{0}' is invalid.", format), e);
            }
        }

        switch (thisFmt.ToUpper())
        {
            // Binary formatting.
            case "B":
                baseNumber = 2;
                break;
            case "O":
                baseNumber = 8;
                break;
            case "H":
                baseNumber = 16;
                break;
            // Handle unsupported format strings.
            default:
                try
                {
                    return HandleOtherFormats(format, arg);
                }
                catch (FormatException e)
                {
                    throw new FormatException(String.Format("The format of '{0}' is invalid.", format), e);
                }
        }

        // Return a formatted string.
        string numericString = String.Empty;
        for (int ctr = bytes.GetUpperBound(0); ctr >= bytes.GetLowerBound(0); ctr--)
        {
            string byteString = Convert.ToString(bytes[ctr], baseNumber);
            if (baseNumber == 2)
                byteString = new String('0', 8 - byteString.Length) + byteString;
            else if (baseNumber == 8)
                byteString = new String('0', 4 - byteString.Length) + byteString;
            // Base is 16.
            else
                byteString = new String('0', 2 - byteString.Length) + byteString;

            numericString += byteString + " ";
        }
        return numericString.Trim();
    }

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

MyFormatter次の例に示すように、 オブジェクトを MyFormatter メソッドのFormatパラメーターとしてprovider渡すことで、カスタム書式を提供するためにを使用できます。

C#
public class Example
{
    public static void Main()
    {
        Console.WindowWidth = 100;

        byte byteValue = 124;
        Console.WriteLine(String.Format(new MyFormatter(),
                                        "{0} (binary: {0:B}) (hex: {0:H})", byteValue));

        int intValue = 23045;
        Console.WriteLine(String.Format(new MyFormatter(),
                                        "{0} (binary: {0:B}) (hex: {0:H})", intValue));

        ulong ulngValue = 31906574882;
        Console.WriteLine(String.Format(new MyFormatter(),
                                        "{0}\n   (binary: {0:B})\n   (hex: {0:H})",
                                        ulngValue));

        BigInteger bigIntValue = BigInteger.Multiply(Int64.MaxValue, 2);
        Console.WriteLine(String.Format(new MyFormatter(),
                                        "{0}\n   (binary: {0:B})\n   (hex: {0:H})",
                                        bigIntValue));
    }
}
// The example displays the following output:
//    124 (binary: 01111100) (hex: 7c)
//    23045 (binary: 00000000 00000000 01011010 00000101) (hex: 00 00 5a 05)
//    31906574882
//       (binary: 00000000 00000000 00000000 00000111 01101101 11000111 10110010 00100010)
//       (hex: 00 00 00 07 6d c7 b2 22)
//    18446744073709551614
//       (binary: 00000000 11111111 11111111 11111111 11111111 11111111 11111111 11111111 11111110)
//       (hex: 00 ff ff ff ff ff ff ff fe)

注釈

ICustomFormatter.Format はコールバック メソッドです。 これは、 や StringBuilder.AppendFormat(IFormatProvider, String, Object[])などのString.Format(IFormatProvider, String, Object[])カスタム書式設定をサポートするメソッドによって呼び出されます。 実装は、 複合書式指定文字列内の書式指定項目ごとに 1 回呼び出されます。 たとえば、次のステートメントでは、 ICustomFormatter.Format メソッドは 3 回呼び出されます。

C#
Console.WriteLine(String.Format(new MyFormatter(),
                                "{0} (binary: {0:B}) (hex: {0:H})", byteValue));

パラメーターは arg 、0 から始まる位置が特定の書式項目のインデックスに対応するオブジェクト リスト内のオブジェクトです。

パラメーターには format 、書式指定項目の formatString コンポーネントである書式指定文字列が含まれています。 書式項目にコンポーネントがない formatString 場合、 の format 値は です null。 が nullの場合formatは、 のarg種類に応じて、選択した既定の書式指定を使用できる場合があります。

パラメーターは formatProvider 、 の IFormatProvider 書式設定を提供する実装です arg。 通常は、実装の ICustomFormatter インスタンスです。 が の場合 formatProvidernullそのパラメーターは無視されます。

.NET FrameworkでFormatサポートされていない書式設定を提供できるように、 メソッドの実装には次の機能が含まれている必要があります。 書式メソッドで書式がサポートされていない場合は、書式設定されているオブジェクトが インターフェイスを IFormattable 実装しているかどうかを判断します。 その場合は、そのインターフェイスの メソッドを IFormattable.ToString 呼び出します。 それ以外の場合は、基になるオブジェクトの既定 Object.ToString のメソッドを呼び出します。 次のコードは、このパターンを示しています。

C#
if (arg is IFormattable)
    return ((IFormattable)arg).ToString(format, CultureInfo.CurrentCulture);
else if (arg != null)
    return arg.ToString();

適用対象

製品 バージョン
.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, 8, 9, 10
.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, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

こちらもご覧ください