IFormatProvider.GetFormat(Type) Méthode

Définition

Retourne un objet qui assure des services de mise en forme pour le type spécifié.Returns an object that provides formatting services for the specified type.

public:
 System::Object ^ GetFormat(Type ^ formatType);
public object GetFormat (Type formatType);
abstract member GetFormat : Type -> obj
Public Function GetFormat (formatType As Type) As Object

Paramètres

formatType
Type

Objet qui spécifie le type d'objet de format à retourner.An object that specifies the type of format object to return.

Retours

Une instance de l'objet spécifié par formatType, si l'implémentation IFormatProvider peut fournir ce type d'objet ; sinon, null.An instance of the object specified by formatType, if the IFormatProvider implementation can supply that type of object; otherwise, null.

Exemples

L’exemple suivant illustre l’utilisation d’une classe qui implémente l' IFormatProvider interface et la GetFormat méthode.The following example illustrates the use of a class that implements the IFormatProvider interface and the GetFormat method. La AcctNumberFormat classe convertit Int64 une valeur qui représente un numéro de compte en numéro de compte à 12 chiffres mis en forme.The AcctNumberFormat class converts an Int64 value that represents an account number to a formatted 12-digit account number. Sa GetFormat méthode retourne une référence à elle-même formatType si le paramètre fait référence à ICustomFormatterune classe qui implémente GetFormat ; nullsinon, retourne.Its GetFormat method returns a reference to itself if the formatType parameter refers to a class that implements ICustomFormatter; otherwise, GetFormat returns null.

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;
   }
}
Public Class AcctNumberFormat : Implements IFormatProvider, ICustomFormatter

   Private Const ACCT_LENGTH As Integer = 12
   
   Public Function GetFormat(formatType As Type) As Object _
                   Implements IFormatProvider.GetFormat
      If formatType Is GetType(ICustomFormatter) Then
         Return Me
      Else
         Return Nothing
      End If
   End Function
   
   Public Function Format(fmt As String, arg As Object, formatProvider As IFormatProvider) As String _
                          Implements ICustomFormatter.Format

      ' Provide default formatting if arg is not an Int64.
       If Not TypeOf arg Is Int64 Then
         Try 
            Return HandleOtherFormats(fmt, arg) 
         Catch e As FormatException 
            Throw New FormatException(String.Format("The format of '{0}' is invalid.", fmt), e)
         End Try
       End If   
                     
      ' Provider default formatting for unsupported format strings.
      Dim ufmt As String = fmt.ToUpper(CultureInfo.InvariantCulture)
      If Not (ufmt = "H" Or ufmt = "I") Then
         Try
            Return HandleOtherFormats(fmt, arg)
         Catch e As FormatException 
            Throw New FormatException(String.Format("The format of '{0}' is invalid.", fmt), e)
         End Try
      End If   

      ' Convert argument to a string.
      Dim result As String = arg.ToString()
      
      ' If account number is less than 12 characters, pad with leading zeroes.
      If result.Length < ACCT_LENGTH Then result = result.PadLeft(ACCT_LENGTH, "0"c)
      ' If account number is more than 12 characters, truncate to 12 characters.
      If result.Length > ACCT_LENGTH Then result = Left(result, ACCT_LENGTH)   
      
      If ufmt = "I"                              ' Integer-only format.
         Return result
      ' Add hyphens for H format specifier.
      Else                                       ' Hypenated format.
         Return Left(result, 5) & "-" & Mid(result, 6, 3) & "-" & Right(result, 4)
      End If   
   End Function   

   Private Function HandleOtherFormats(fmt As String, arg As Object) As String
      If TypeOf arg Is IFormattable Then
         Return DirectCast(arg, IFormattable).ToString(fmt, CultureInfo.CurrentCulture)
      ElseIf arg IsNot Nothing Then
         Return arg.ToString()
      Else
         Return String.Empty
      End If
   End Function
End Class

Une instance de la AcctNumberFormat classe peut ensuite être passée comme argument à une méthode qui fournit des services de mise en forme ou d’analyse.An instance of the AcctNumberFormat class can then be passed as an argument to a method that provides formatting or parsing services. Par exemple, le code suivant passe une AcctNumberFormat classe à la String.Format(IFormatProvider, String, Object[]) méthode pour générer un numéro de compte à 12 chiffres mis en forme.For example, the following code passes an AcctNumberFormat class to the String.Format(IFormatProvider, String, Object[]) method to generate a formatted 12-digit account number.

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.
Imports System.Globalization

Public Enum DaysOfWeek As Long
   Monday = 1
   Tuesday = 2
End Enum

Module TestFormatting
   Public Sub Main()
      Dim acctNumber As Long, balance As Double 
      Dim wday As DaysOfWeek 
      Dim output As String

      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)
   End Sub
End Module
' 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.

Remarques

GetFormatest une méthode de rappel que les méthodes de mise en forme et d’analyse appellent pour récupérer des informations sur le format de la chaîne d’entrée dans les opérations d’analyse ou le format de la chaîne de sortie dans les opérations de mise en forme.GetFormat is a callback method that formatting and parsing methods invoke to retrieve information about the format of the input string in parsing operations or the format of the output string in formatting operations. Dans le formatType paramètre, la méthode de mise en forme ou d’analyse passe le type d’objet dont elle a besoin pour effectuer son opération.In the formatType parameter, the formatting or parsing method passes the type of object it requires to perform its operation. Si l' IFormatProvider implémentation peut fournir cet objet de mise en forme ou d’analyse, il retourne cet objet.If the IFormatProvider implementation can supply this formatting or parsing object, it returns that object. Si ce n’est pas nullle cas, elle retourne.If not, it returns null.

Par exemple, dans l’appel à la Int32.ToString(IFormatProvider) méthode, l’argument de la méthode IFormatProvider est un objet qui fournit des informations sur la manière dont la représentation sous forme de chaîne de l’instance entière actuelle peut être mise en forme.For example, in the call to the Int32.ToString(IFormatProvider) method, the method argument is an IFormatProvider object that provides information about how the string representation of the current integer instance might be formatted. Lorsque le runtime exécute la méthode, IFormatProvider il appelle la méthode de GetFormat l’objet et lui passe un Type objet qui représente le NumberFormatInfo type.When the runtime executes the method, it calls the IFormatProvider object's GetFormat method and passes it a Type object that represents the NumberFormatInfo type. Si l' IFormatProvider objet peut fournir un NumberFormatInfo objet, il retourne cet objet.If the IFormatProvider object can supply a NumberFormatInfo object, it returns that object. S’il ne peut pas fournir un objet de ce type, nullil retourne.If it cannot supply an object of that type, it returns null.

Vous pouvez implémenter IFormatProvider l’interface et GetFormat la méthode dans des classes qui fournissent des services de mise en forme ou d’analyse personnalisés.You can implement the IFormatProvider interface and the GetFormat method in classes that provide custom formatting or parsing services. L' IFormatProvider implémentation est ensuite passée comme argument à toute surcharge d’une méthode d’analyse ou de mise en forme qui a un paramètre de IFormatProvidertype, tel String.Format(IFormatProvider, String, Object[])que Int32.ToString(String, IFormatProvider), ou DateTime.Parse(String, IFormatProvider).The IFormatProvider implementation is then passed as an argument to any overload of a parsing or formatting method that has a parameter of type IFormatProvider, such as String.Format(IFormatProvider, String, Object[]), Int32.ToString(String, IFormatProvider), or DateTime.Parse(String, IFormatProvider).

S’applique à