IFormatProvider インターフェイス

書式を制御するオブジェクトを取得するための機構を提供します。

この型のすべてのメンバの一覧については、IFormatProvider メンバ を参照してください。

Public Interface IFormatProvider
[C#]
public interface IFormatProvider
[C++]
public __gc __interface IFormatProvider
[JScript]
public interface IFormatProvider

IFormatProvider を実装するクラス

クラス 説明
CultureInfo カルチャの名前、書記体系、使用する暦などの特定のカルチャに関する情報を表し、カルチャ固有のオブジェクトにアクセスできるようにします。このオブジェクトは、日付の形式の指定や文字列の並べ替えなどの共通の操作を行うための情報を提供します。
DateTimeFormatInfo カルチャに従って、 DateTime 値を形式指定および表示する方法を定義します。
NumberFormatInfo カルチャに応じて、数値を形式指定および表示する方法を定義します。

解説

共通言語ランタイムの一部のメソッドは、値を文字列形式に、または文字列形式を値に変換し、1 つ以上の文字が含まれた、書式指定子と呼ばれる文字列パラメータを受け取ります。この書式指定子は、値の変換方法を示します。書式指定子の意味がカルチャによって異なる場合は、文字列形式で使用される実際の文字が書式指定オブジェクトによって提供されます。

クラス型または値型は、このインターフェイスの GetFormat メソッドを実装して、書式情報や実装型の処理を提供するオブジェクトを取得します。

たとえば、 IFormatProvider は、 NumberFormatInfoDateTimeFormatInfo によって実装されます。 NumberFormatInfo は、基本データ型の数値を書式指定するときに使用するカルチャ固有の情報を提供し、 DateTimeFormatInfo は日時の値の形式を指定するときに使用するカルチャ固有の情報を提供します。

使用例

[Visual Basic, C#, C++] 次のコード例は、 IFormatProvider インターフェイスと GetFormat メソッドを実装したクラスの使用方法を示したものです。AnyRadix クラスは、"Ra" 書式設定コードをサポートし、 Int64 の値を 2 ~ 36 の指定された基数の文字列に変換します。 GetFormat は、Type パラメータが ICustomFormatter を実装したクラスを参照している場合は、自分自身への参照を返します。それ以外の場合、 GetFormat は null 参照 (Visual Basic では Nothing) を返します。

 
' Sample for the IFormatProvider interface and
' the IFormatProvider.GetFormat( Type ) method.
Imports System
Imports Microsoft.VisualBasic

' This class implements the "Ra" formatting code. An instance of this 
' class should be passed to methods requiring an IFormatProvider.
Public Class AnyRadix
    Implements ICustomFormatter 
    Implements IFormatProvider

    ' The value to be formatted is returned as a signed string 
    ' of digits from the rDigits array. 
    Const radixCode As String = "Ra"
    Private Shared rDigits As Char( ) = { _
        "0"c, "1"c, "2"c, "3"c, "4"c, "5"c, "6"c, "7"c, "8"c, _
        "9"c, "A"c, "B"c, "C"c, "D"c, "E"c, "F"c, "G"c, "H"c, _
        "I"c, "J"c, "K"c, "L"c, "M"c, "N"c, "O"c, "P"c, "Q"c, _
        "R"c, "S"c, "T"c, "U"c, "V"c, "W"c, "X"c, "Y"c, "Z"c }
        
    ' This method returns an object that implements ICustomFormatter 
    ' to do the formatting. 
    Public Function GetFormat( argType As Type ) As Object _
        Implements IFormatProvider.GetFormat

        ' Here, the same object (Me) is returned, but it would be 
        ' possible to return an object of a different type.
        If argType Is GetType( ICustomFormatter ) Then
            Return Me
        Else
            Return Nothing
        End If
    End Function 
        
    ' This method does the formatting only if it recognizes the 
    ' format codes. 
    Public Function Format( formatString As String, _
        argToBeFormatted As Object, _
        provider As IFormatProvider ) As String _
        Implements ICustomFormatter.Format
            
        ' If no format string is provided or the format string cannot 
        ' be handled, use IFormattable or standard string processing.
        If formatString Is Nothing OrElse _
            Not formatString.Trim( ).StartsWith( radixCode ) Then

            If TypeOf argToBeFormatted Is IFormattable Then
                Return CType( argToBeFormatted, IFormattable ). _
                    ToString( formatString, provider )
            Else
                Return argToBeFormatted.ToString( )
            End If
        End If 

        ' The formatting is handled here.
        Dim digitIndex          As Integer = 0
        Dim radix               As Long 
        Dim longToBeFormatted   As Long 
        Dim longPositive        As Long
        Dim outDigits( 63 )     As Char
            
        ' Extract the radix from the format string.
        formatString = formatString.Replace( radixCode, "" )
        Try
            radix = Convert.ToInt64( formatString )
        Catch ex As Exception
            Throw New ArgumentException( String.Format( _
                "The radix ""{0}"" is invalid.", _
                formatString ), ex )
        End Try

        ' Verify that the radix is in the proper range.
        If radix < 2 OrElse radix > 36 Then
            Throw New ArgumentException( String.Format( _
                "The radix ""{0}"" is not in the range 2..36.", _
                formatString ) )
        End If
            
        ' Verify that the argument can be converted to a long integer.
        Try
            longToBeFormatted = CType( argToBeFormatted, Long )
        Catch ex As Exception
            Throw New ArgumentException( String.Format( _
                "The argument ""{0}"" cannot be " & _
                "converted to an integer value.", _
                argToBeFormatted ), ex )
        End Try
            
        ' Extract the magnitude for conversion.
        longPositive = Math.Abs( longToBeFormatted )

        ' Convert the magnitude to a digit string.
        For digitIndex = 0 To 64
            If longPositive = 0 Then Exit For

            outDigits( outDigits.Length - digitIndex - 1 ) = _
                rDigits( longPositive Mod radix )
            longPositive \= radix
        Next digitIndex
            
        ' Add a minus sign if the argument is negative.
        If longToBeFormatted < 0 Then
            outDigits( outDigits.Length - digitIndex - 1 ) = "-"c 
            digitIndex += 1
        End If 

        Return New String( outDigits, _
            outDigits.Length - digitIndex, digitIndex )
    End Function 
End Class

Module IFormatProviderDemo
    
    Sub ConvertToAnyRadix( argToConvert As Object, _
        formatStr As String )

        Dim provider As New AnyRadix( )
        Dim messageStr As String = _
            String.Format( "{{0:{0}}}", formatStr )

        ' Write the first part of the output line.
        Console.Write( "{0,18}  {1,-6}", _ 
            argToConvert, formatStr )

        ' Convert the specified argument using the specified format.
        Try
            Console.WriteLine( String.Format( _
                provider, messageStr, argToConvert ) )
        Catch ex As Exception
            Dim lineEnd As Integer = _
                ex.ToString( ).IndexOf( vbLf )
            Console.WriteLine( _
                ex.ToString( ).Substring( 0, lineEnd ) )
            Console.WriteLine( )
        End Try
    End Sub 
        
    Sub Main( )
        Dim TwoToThe32      As Long = 4294967296
        Dim fifteenNines    As Long = 999999999999999
            
        Console.WriteLine( _
            "This example of the IFormatProvider interface " & _
            vbCrLf & "and the IFormatProvider." & _
            "GetFormat( Type ) method " & vbCrLf & _
            "generates the following output." & vbCrLf )
        Console.WriteLine( "{0,18} Format Result", "Number" )
        Console.WriteLine( "{0,18} ------ ------", "------" )
            
        ' These are valid conversions.
        ConvertToAnyRadix( TwoToThe32, "Ra2" )
        ConvertToAnyRadix( TwoToThe32, "Ra5" )
        ConvertToAnyRadix( TwoToThe32, "Ra16" )
        ConvertToAnyRadix( TwoToThe32, "Ra23" )
        ConvertToAnyRadix( TwoToThe32, "Ra36" )
        ConvertToAnyRadix( fifteenNines, "Ra2" )
        ConvertToAnyRadix( fifteenNines, "Ra3" )
        ConvertToAnyRadix( fifteenNines, "Ra8" )
        ConvertToAnyRadix( fifteenNines, "Ra11" )
        ConvertToAnyRadix( fifteenNines, "Ra16" )
        ConvertToAnyRadix( fifteenNines, "Ra23" )
        ConvertToAnyRadix( fifteenNines, "Ra36" )
        ConvertToAnyRadix( fifteenNines, "E16" )
        ConvertToAnyRadix( fifteenNines, "" )
            
        ' These are error conditions.
        ConvertToAnyRadix( fifteenNines, "Ra37" )
        ConvertToAnyRadix( "ABCDEFGHIJKLM", "Ra16" )
    End Sub 
End Module 

' This example of the IFormatProvider interface
' and the IFormatProvider.GetFormat( Type ) method
' generates the following output.
' 
'             Number Format Result
'             ------ ------ ------
'         4294967296  Ra2   100000000000000000000000000000000
'         4294967296  Ra5   32244002423141
'         4294967296  Ra16  100000000
'         4294967296  Ra23  1606K7IC
'         4294967296  Ra36  1Z141Z4
'    999999999999999  Ra2   11100011010111111010100100110001100111111111111111
'    999999999999999  Ra3   11212010201001210101011021212000
'    999999999999999  Ra8   34327724461477777
'    999999999999999  Ra11  26A6A3689065639
'    999999999999999  Ra16  38D7EA4C67FFF
'    999999999999999  Ra23  1134DIFHLMM4
'    999999999999999  Ra36  9UGXNORJLR
'    999999999999999  E16   9.9999999999999900E+014
'    999999999999999        999999999999999
'    999999999999999  Ra37  System.ArgumentException: The radix "37" is not in
' the range 2..36.
' 
'      ABCDEFGHIJKLM  Ra16  System.ArgumentException: The argument "ABCDEFGHIJK
' LM" cannot be converted to an integer value. ---> System.InvalidCastException
' : Cast from string "ABCDEFGHIJKLM" to type 'Long' is not valid. ---> System.F
' ormatException: Input string was not in a correct format.

[C#] 
// Sample for the IFormatProvider interface and
// the IFormatProvider.GetFormat( Type ) method.
using System;

// This class implements the "Ra" formatting code. An instance of this 
// class should be passed to methods requiring an IFormatProvider.
public class AnyRadix : ICustomFormatter, IFormatProvider
{
    // The value to be formatted is returned as a signed string 
    // of digits from the rDigits array. 
    const string radixCode = "Ra";
    private static char[] rDigits = {
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 
        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 
        'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 
        'U', 'V', 'W', 'X', 'Y', 'Z' };
        
    // This method returns an object that implements ICustomFormatter 
    // to do the formatting. 
    public object GetFormat( Type argType )
    {
        // Here, the same object (this) is returned, but it would 
        // be possible to return an object of a different type.
        if ( argType == typeof( ICustomFormatter ) )
            return this;
        else
            return null;
    } 
        
    // This method does the formatting only if it recognizes the 
    // format codes. 
    public string Format( string formatString, 
        object argToBeFormatted, IFormatProvider provider )
    {
        // If no format string is provided or the format string cannot 
        // be handled, use IFormattable or standard string processing.
        if( formatString == null || 
            ! formatString.Trim( ).StartsWith( radixCode ) )
        {
            if( argToBeFormatted is IFormattable )
                return ( (IFormattable)argToBeFormatted ).
                    ToString( formatString, provider );
            else
                return argToBeFormatted.ToString( );
        }

        // The formatting is handled here.
        int     digitIndex = 0;
        long    radix;
        long    longToBeFormatted;
        long    longPositive;
        char[ ] outDigits = new char[ 63 ];
            
        // Extract the radix from the format string.
        formatString = formatString.Replace( radixCode, "" );
        try
        {
            radix = Convert.ToInt64( formatString );
        }
        catch( Exception ex )
        {
            throw new ArgumentException( String.Format( 
                "The radix \"{0}\" is invalid.", 
                formatString ), ex );
        }

        // Verify that the radix is in the proper range.
        if( radix <2 || radix > 36 )
            throw new ArgumentException( String.Format( 
                "The radix \"{0}\" is not in the range 2..36.", 
                formatString ) );
            
        // Verify that the argument can be converted to a long integer.
        try
        {
            longToBeFormatted = (long)argToBeFormatted;
        }
        catch( Exception ex )
        {
            throw new ArgumentException( String.Format(
                "The argument \"{0}\" cannot be " +
                "converted to an integer value.", 
                argToBeFormatted ), ex );
        }
            
        // Extract the magnitude for conversion.
        longPositive = Math.Abs( longToBeFormatted );

        // Convert the magnitude to a digit string.
        for( digitIndex = 0; digitIndex <= 64; digitIndex++ )
        {
            if( longPositive == 0 ) break;

            outDigits[ outDigits.Length - digitIndex - 1 ] = 
                rDigits[ longPositive % radix ];
            longPositive /= radix;
        }
            
        // Add a minus sign if the argument is negative.
        if( longToBeFormatted < 0 )
            outDigits[ outDigits.Length - digitIndex++ - 1 ] = 
                '-';

        return new string( outDigits, 
            outDigits.Length - digitIndex, digitIndex );
    } 
} 

class IFormatProviderDemo
{
    static void ConvertToAnyRadix( object argToConvert, 
        string formatStr )
    {
        AnyRadix    provider = new AnyRadix( );
        string      messageStr = 
            String.Format( "{{0:{0}}}", formatStr );

        // Write the first part of the output line.
        Console.Write( "{0,18}  {1,-6}", argToConvert, formatStr );

        // Convert the specified argument using the specified format.
        try
        {
            Console.WriteLine( String.Format( 
                provider, messageStr, argToConvert ) );
        }
        catch( Exception ex )
        {
            // Display the exception without the stack trace.
            int lineEnd = ex.ToString( ).IndexOf( '\n' );
            Console.WriteLine( "{0}\n",
                ex.ToString( ).Substring( 0, lineEnd ) );
        }
    } 
        
    static void Main( )
    {
        long twoToThe32 = 4294967296;
        long fifteenNines = 999999999999999;
            
        Console.WriteLine(
            "This example of the IFormatProvider interface \n" +
            "and the IFormatProvider.GetFormat( Type ) method " +
            "\ngenerates the following output.\n" );
        Console.WriteLine( "{0,18} Format Result", "Number" );
        Console.WriteLine( "{0,18} ------ ------", "------" );
            
        // These are valid conversions.
        ConvertToAnyRadix( twoToThe32, "Ra2" );
        ConvertToAnyRadix( twoToThe32, "Ra5" );
        ConvertToAnyRadix( twoToThe32, "Ra16" );
        ConvertToAnyRadix( twoToThe32, "Ra23" );
        ConvertToAnyRadix( twoToThe32, "Ra36" );
        ConvertToAnyRadix( fifteenNines, "Ra2" );
        ConvertToAnyRadix( fifteenNines, "Ra3" );
        ConvertToAnyRadix( fifteenNines, "Ra8" );
        ConvertToAnyRadix( fifteenNines, "Ra11" );
        ConvertToAnyRadix( fifteenNines, "Ra16" );
        ConvertToAnyRadix( fifteenNines, "Ra23" );
        ConvertToAnyRadix( fifteenNines, "Ra36" );
        ConvertToAnyRadix( fifteenNines, "E16" );
        ConvertToAnyRadix( fifteenNines, "" );
            
        // These are error conditions.
        ConvertToAnyRadix( fifteenNines, "Ra37" );
        ConvertToAnyRadix( "ABCDEFGHIJKLM", "Ra16" );
    } 
} 

/*
This example of the IFormatProvider interface
and the IFormatProvider.GetFormat( Type ) method
generates the following output.

            Number Format Result
            ------ ------ ------
        4294967296  Ra2   100000000000000000000000000000000
        4294967296  Ra5   32244002423141
        4294967296  Ra16  100000000
        4294967296  Ra23  1606K7IC
        4294967296  Ra36  1Z141Z4
   999999999999999  Ra2   11100011010111111010100100110001100111111111111111
   999999999999999  Ra3   11212010201001210101011021212000
   999999999999999  Ra8   34327724461477777
   999999999999999  Ra11  26A6A3689065639
   999999999999999  Ra16  38D7EA4C67FFF
   999999999999999  Ra23  1134DIFHLMM4
   999999999999999  Ra36  9UGXNORJLR
   999999999999999  E16   9.9999999999999900E+014
   999999999999999        999999999999999
   999999999999999  Ra37  System.ArgumentException: The radix "37" is not in th
e range 2..36.

     ABCDEFGHIJKLM  Ra16  System.ArgumentException: The argument "ABCDEFGHIJKLM
" cannot be converted to an integer value. ---> System.InvalidCastException: Sp
ecified cast is not valid.
*/

[C++] 
// Sample for the IFormatProvider interface and
// the IFormatProvider::GetFormat( Type* ) method.
#using <mscorlib.dll>
using namespace System;

// This class implements the "Ra" formatting code. An instance of this 
// class should be passed to methods requiring an IFormatProvider.
__gc class AnyRadix : public IFormatProvider, public ICustomFormatter
{
    static Object* null = 0;

    // The value to be formatted is returned as a signed string 
    // of digits from the rDigits array. 
    static String* radixCode = S"Ra";
    static Char rDigits[ ] = {
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 
        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 
        'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 
        'U', 'V', 'W', 'X', 'Y', 'Z' };
        
    // This method returns an object that implements ICustomFormatter 
    // to do the formatting. 
    public: Object* GetFormat( Type* argType )
    {
        // Here, the same object (this) is returned, but it would 
        // be possible to return an object of a different type.
        if( argType == __typeof( ICustomFormatter ) ) 
            return this;
        else
            return null;
    } 
        
    // This method does the formatting only if it recognizes the 
    // format codes. 
    public: String* Format( String* formatString, 
        Object* argToBeFormatted, IFormatProvider* provider )
    {
        // If no format string is provided or the format string cannot 
        // be handled, use IFormattable or standard string processing.
        if( formatString == null || 
            ! formatString->Trim( )->StartsWith( radixCode ) )
        {
            if( dynamic_cast<IFormattable*>( argToBeFormatted ) != 0 )
                return static_cast<IFormattable*>( argToBeFormatted )->
                    ToString( formatString, provider );
            else
                return argToBeFormatted->ToString(); 
        }

        // The formatting is handled here.
        int         digitIndex = 0;
        __int64     radix;
        __int64     longToBeFormatted;
        __int64     longPositive;
        Char        outDigits[] = __gc new Char[ 64 ];
            
        // Extract the radix from the format string.
        formatString = formatString->Replace( radixCode, "" );
        try
        {
            radix = Convert::ToInt64( formatString );
        }
        catch( Exception* ex )
        {
            throw new ArgumentException( String::Format( 
                S"The radix \"{0}\" is invalid.\n", 
                    formatString ), ex );
        }

        // Verify that the radix is in the proper range.
        if( radix <2 || radix > 36 )
            throw new ArgumentException( String::Format(
                S"The radix \"{0}\" is not in the range 2..36.", 
                formatString ) );
            
        // Verify that the argument can be converted to a long integer.
        try
        {
            longToBeFormatted = 
                * static_cast<__box __int64 *>( argToBeFormatted );
        }
        catch( Exception* ex )
        {
            throw new ArgumentException( String::Format(
                S"The argument \"{0}\" cannot be " 
                S"converted to an integer value.", 
                argToBeFormatted ), ex );
        }
            
        // Extract the magnitude for conversion.
        longPositive = Math::Abs( longToBeFormatted );

        // Convert the magnitude to a digit string.
        for( digitIndex = 0; longPositive != 0 && digitIndex <= 64; 
            digitIndex++ )
        {
            outDigits[ outDigits->Length - digitIndex - 1 ] = 
                rDigits[ longPositive % radix ];
            longPositive /= radix;
        }
            
        // Add a minus sign if the argument is negative.
        if( longToBeFormatted < 0 )
            outDigits[ outDigits->Length - digitIndex++ - 1 ] = '-';

        return new String( outDigits, 
            outDigits->Length - digitIndex, digitIndex );
    } 
}; 

void ConvertToAnyRadix( Object* argToConvert, String* formatStr )
{
    AnyRadix*    provider = new AnyRadix( );
    String*      messageStr = 
        String::Format( S"{{0:{0}}}", formatStr );

    // Write the first part of the output line.
    Console::Write( S"{0,18}  {1,-6}", argToConvert, formatStr );

    // Convert the specified argument using the specified format.
    try
    {
        Object*     argArray __gc [] = { argToConvert };
        Console::WriteLine( String::Format( 
            provider, messageStr, argArray ) );
    }
    catch( Exception* ex )
    {
        // Display the exception without the stack trace.
        int     lineEnd = ex->ToString( )->IndexOf( '\n' );
        Console::WriteLine( S"{0}\n",
            ex->ToString( )->Substring( 0, lineEnd ) );
    }
} 
    
void main( )
{
    __int64     twoToThe32 = 4294967296;
    __int64     fifteenNines = 999999999999999;
        
    Console::WriteLine(
        S"This example of the IFormatProvider interface \n" 
        S"and the IFormatProvider::GetFormat( Type* ) method " 
        S"\ngenerates the following output.\n" );
    Console::WriteLine( S"{0,18} Format Result", S"Number" );
    Console::WriteLine( S"{0,18} ------ ------", S"------" );
        
    // These are valid conversions.
    ConvertToAnyRadix( __box( twoToThe32 ), S"Ra2" );
    ConvertToAnyRadix( __box( twoToThe32 ), S"Ra5" );
    ConvertToAnyRadix( __box( twoToThe32 ), S"Ra16" );
    ConvertToAnyRadix( __box( twoToThe32 ), S"Ra23" );
    ConvertToAnyRadix( __box( twoToThe32 ), S"Ra36" );
    ConvertToAnyRadix( __box( fifteenNines ), S"Ra2" );
    ConvertToAnyRadix( __box( fifteenNines ), S"Ra3" );
    ConvertToAnyRadix( __box( fifteenNines ), S"Ra8" );
    ConvertToAnyRadix( __box( fifteenNines ), S"Ra11" );
    ConvertToAnyRadix( __box( fifteenNines ), S"Ra16" );
    ConvertToAnyRadix( __box( fifteenNines ), S"Ra23" );
    ConvertToAnyRadix( __box( fifteenNines ), S"Ra36" );
    ConvertToAnyRadix( __box( fifteenNines ), S"E16" );
    ConvertToAnyRadix( __box( fifteenNines ), S"" );
        
    // These are error conditions.
    ConvertToAnyRadix( __box( fifteenNines ), S"Ra37" );
    ConvertToAnyRadix( S"ABCDEFGHIJKLM", S"Ra16" );
} 

/*
This example of the IFormatProvider interface
and the IFormatProvider::GetFormat( Type* ) method
generates the following output.

            Number Format Result
            ------ ------ ------
        4294967296  Ra2   100000000000000000000000000000000
        4294967296  Ra5   32244002423141
        4294967296  Ra16  100000000
        4294967296  Ra23  1606K7IC
        4294967296  Ra36  1Z141Z4
   999999999999999  Ra2   11100011010111111010100100110001100111111111111111
   999999999999999  Ra3   11212010201001210101011021212000
   999999999999999  Ra8   34327724461477777
   999999999999999  Ra11  26A6A3689065639
   999999999999999  Ra16  38D7EA4C67FFF
   999999999999999  Ra23  1134DIFHLMM4
   999999999999999  Ra36  9UGXNORJLR
   999999999999999  E16   9.9999999999999900E+014
   999999999999999        999999999999999
   999999999999999  Ra37  System.ArgumentException: The radix "37" is not in th
e range 2..36.

     ABCDEFGHIJKLM  Ra16  System.ArgumentException: The argument "ABCDEFGHIJKLM
" cannot be converted to an integer value. ---> System.InvalidCastException: Sp
ecified cast is not valid.
*/

[JScript] JScript のサンプルはありません。Visual Basic、C#、および C++ のサンプルを表示するには、このページの左上隅にある言語のフィルタ ボタン 言語のフィルタ をクリックします。

必要条件

名前空間: System

プラットフォーム: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 ファミリ, .NET Compact Framework - Windows CE .NET

アセンブリ: Mscorlib (Mscorlib.dll 内)

参照

IFormatProvider メンバ | System 名前空間 | ICustomFormatter | IFormattable