Cette page vous a-t-elle été utile ?
Votre avis sur ce contenu est important. N'hésitez pas à nous faire part de vos commentaires.
Vous avez d'autres commentaires ?
1500 caractères restants
GetFormat, méthode
Collapse the table of content
Expand the table of content

IFormatProvider.GetFormat, méthode

Obtient un objet fournissant les services de mise en forme pour le type spécifié.

Espace de noms : System
Assembly : mscorlib (dans mscorlib.dll)

Object GetFormat (
	Type formatType
)
Object GetFormat (
	Type formatType
)
function GetFormat (
	formatType : Type
) : Object

Paramètres

formatType

Objet spécifiant le type d'objet de format à obtenir.

Valeur de retour

Instance en cours, si formatType est du même type que l'instance en cours ; sinon référence Null (Nothing en Visual Basic).

Implémentez cette méthode dans des classes qui utilisent les objets de format dans des méthodes qui génèrent ou analysent les représentations sous forme de chaîne d'objets. Les méthodes ToString et Parse sont des exemples de ces types de méthodes.

Pour plus d'informations, consultez la rubrique CultureInfo.CurrentCulture.

L'exemple de code suivant illustre l'utilisation d'une classe qui implémente l'interface IFormatProvider et la méthode GetFormat. La classe AnyRadix prend en charge le code de mise en forme « Ra » et convertit une valeur Int64 en chaîne de n'importe quelle base spécifiée comprise entre 2 et 36. GetFormat retourne une référence à lui-même si le paramètre Type fait référence à une classe qui implémente ICustomFormatter ; dans le cas contraire, GetFormat retourne référence Null (Nothing en Visual Basic).

// 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.
*/

// Sample for the IFormatProvider interface and
// the IFormatProvider.GetFormat( Type ) method.
import System.*;

// 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,IFormatProvider
{
    // The value to be formatted is returned as a signed string 
    // of digits from the rDigits array. 
    private 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.Equals(ICustomFormatter.class.ToType()) ) {
            return this ;
        }
        else {
            return null ;
        }
    } //GetFormat
    
    // 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 instanceof 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(System.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)System.Convert.ToUInt64(argToBeFormatted);
        }
        catch(System.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 = System.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[(int)(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);
    } //Format
} //AnyRadix

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((IFormatProvider)provider,
                messageStr,new Object[]{ argToConvert}));
        }
        catch(System.Exception ex) {
            // Display the exception without the stack trace.
            int lineEnd = ex.ToString().IndexOf('\n');            
            Console.WriteLine("{0}\n", ex.ToString().Substring(0, lineEnd));
        }
    } //ConvertToAnyRadix  
   
    public static void main(String[] args)
    {
        long twoToThe32 = 4294967296L;
        long fifteenNines = 999999999999999L;

        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(((System.UInt64 )(twoToThe32)), "Ra2");
        ConvertToAnyRadix(((System.UInt64)(twoToThe32)), "Ra5");
        ConvertToAnyRadix(((System.UInt64)(twoToThe32)), "Ra16");
        ConvertToAnyRadix(((System.UInt64)(twoToThe32)), "Ra23");
        ConvertToAnyRadix(((System.UInt64)(twoToThe32)), "Ra36");
        ConvertToAnyRadix(((System.UInt64)(fifteenNines)), "Ra2");
        ConvertToAnyRadix(((System.UInt64)(fifteenNines)), "Ra3");
        ConvertToAnyRadix(((System.UInt64)(fifteenNines)), "Ra8");
        ConvertToAnyRadix(((System.UInt64)(fifteenNines)), "Ra11");
        ConvertToAnyRadix(((System.UInt64)(fifteenNines)), "Ra16");
        ConvertToAnyRadix(((System.UInt64)(fifteenNines)), "Ra23");
        ConvertToAnyRadix(((System.UInt64)(fifteenNines)), "Ra36");
        ConvertToAnyRadix(((System.UInt64)(fifteenNines)), "E16");
        ConvertToAnyRadix(((System.UInt64)(fifteenNines)), "");

        // These are error conditions.
        ConvertToAnyRadix(((System.UInt64)(fifteenNines)), "Ra37");
        ConvertToAnyRadix("ABCDEFGHIJKLM", "Ra16");
    } //main
} //IFormatProviderDemo

/*
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.FormatException: Input str
ing was not in a correct format.
*/

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile pour Pocket PC, Windows Mobile pour Smartphone, Windows Server 2003, Windows XP Édition Media Center, Windows XP Professionnel Édition x64, Windows XP SP2, Windows XP Starter Edition

Le .NET Framework ne prend pas en charge toutes les versions de chaque plate-forme. Pour obtenir la liste des versions prises en charge, consultez Configuration requise.

.NET Framework

Prise en charge dans : 2.0, 1.1, 1.0

.NET Compact Framework

Prise en charge dans : 2.0, 1.0

Ajouts de la communauté

AJOUTER
Afficher:
© 2015 Microsoft