Lire en anglais

Partager via


ICustomFormatter.Format(String, Object, IFormatProvider) Méthode

Définition

Convertit la valeur d’un objet spécifié en représentation sous forme de chaîne équivalente en utilisant les informations de format et de mise en forme spécifiques à la culture spécifiées.

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

Paramètres

format
String

Chaîne de format contenant des spécifications de mise en forme.

arg
Object

Objet à mettre en forme.

formatProvider
IFormatProvider

Objet qui fournit des informations de format sur l’instance actuelle.

Retours

Représentation sous forme de chaîne de la valeur de arg, mise en forme comme spécifiée par format et formatProvider.

Exemples

L’exemple suivant implémente pour autoriser la mise en forme binaire, octale et hexadécimale des valeurs intégrales ICustomFormatter . Son ICustomFormatter.Format implémentation détermine si le paramètre de format est l’une des trois chaînes de format prises en charge (« B » pour binaire, « O » pour octal et « H » pour hexadécimal) et met en forme le arg paramètre de manière appropriée. Sinon, si arg n’est pas null, il appelle l’implémentation arg du IFormattable.ToString paramètre, le cas échéant, ou sa méthode sans ToString paramètre, si elle n’en est pas une. Si arg est null, la méthode retourne 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 peut ensuite être utilisé pour fournir une mise en forme personnalisée en passant un MyFormatter objet comme provider paramètre de la Format méthode, comme le montre l’exemple suivant.

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)

Remarques

ICustomFormatter.Format est une méthode de rappel. Il est appelé par une méthode qui prend en charge la mise en forme personnalisée, telle que String.Format(IFormatProvider, String, Object[]) ou StringBuilder.AppendFormat(IFormatProvider, String, Object[]). L’implémentation est appelée une fois pour chaque élément de format dans une chaîne de format composite. Par exemple, dans l’instruction suivante, la ICustomFormatter.Format méthode est appelée trois fois.

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

Le arg paramètre est l’objet de la liste d’objets dont la position de base zéro correspond à l’index d’un élément de format particulier.

Le format paramètre contient une chaîne de format, qui est le formatString composant d’un élément de format. Si l’élément de format n’a aucun formatString composant, la valeur de format est null. Si format est null, en fonction du type de arg, vous pouvez peut-être utiliser la spécification de format par défaut de votre choix.

Le formatProvider paramètre est l’implémentation IFormatProvider qui fournit la mise en forme pour arg. En règle générale, il s’agit d’un instance de votre ICustomFormatter implémentation. Si formatProvider est null, ignorez ce paramètre.

Votre implémentation de la Format méthode doit inclure les fonctionnalités suivantes afin que .NET Framework puisse fournir une mise en forme que vous ne prenez pas en charge. Si votre méthode de format ne prend pas en charge un format, déterminez si l’objet mis en forme implémente l’interface IFormattable . Si c’est le cas, appelez la IFormattable.ToString méthode de cette interface. Sinon, appelez la méthode par défaut Object.ToString de l’objet sous-jacent. Le code suivant illustre ce modèle.

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

S’applique à

Produit Versions
.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

Voir aussi