ICustomFormatter.Format(String, Object, IFormatProvider) ICustomFormatter.Format(String, Object, IFormatProvider) ICustomFormatter.Format(String, Object, IFormatProvider) ICustomFormatter.Format(String, Object, IFormatProvider) Method

定義

使用指定的格式和特定文化特性 (Culture) 的格式資訊,將指定物件值轉換成相等的字串表示。Converts the value of a specified object to an equivalent string representation using specified format and culture-specific formatting information.

public:
 System::String ^ Format(System::String ^ format, System::Object ^ arg, IFormatProvider ^ formatProvider);
public string Format (string format, object arg, IFormatProvider formatProvider);
abstract member Format : string * obj * IFormatProvider -> string
Public Function Format (format As String, arg As Object, formatProvider As IFormatProvider) As String

參數

format
String String String String

格式字串,包含格式規格。A format string containing formatting specifications.

arg
Object Object Object Object

要格式化的物件。An object to format.

formatProvider
IFormatProvider IFormatProvider IFormatProvider IFormatProvider

物件,可提供目前的執行個體相關格式資訊。An object that supplies format information about the current instance.

傳回

arg 值的字串表示,由 formatformatProvider 根據指示格式化。The string representation of the value of arg, formatted as specified by format and formatProvider.

範例

下列範例會實行ICustomFormatter , 以允許整數值的二進位、八進位和十六進位格式。The following example implements ICustomFormatter to allow binary, octal, and hexadecimal formatting of integral values. ICustomFormatter.Format執行會判斷格式參數是否為三個支援的格式字串之一 (二進位的 "B"、八進位為 "O", 而 "H" 代表十六進位), 並適當arg地格式化參數。Its ICustomFormatter.Format implementation determines whether the format parameter is one of the three supported format strings ("B" for binary, "O" for octal, and "H" for hexadecimal) and formats the arg parameter appropriately. 否則, 如果argnull是, 則會呼叫arg參數的IFormattable.ToString執行 (如果有的話) 或其無ToString參數方法 (如果沒有的話)。Otherwise, if arg is not null, it calls the arg parameter's IFormattable.ToString implementation, if one exists, or its parameterless ToString method, if one does not. 如果 argnull,則方法會傳回 String.EmptyIf arg is null, the method returns String.Empty.

using System;
using System.Globalization;
using System.Numerics;

public class BinaryFormatter : 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;
   }
}
Imports System.Globalization
Imports System.Numerics

Public Class BinaryFormatter : Implements IFormatProvider, ICustomFormatter
   ' IFormatProvider.GetFormat implementation.
   Public Function GetFormat(formatType As Type) As Object _
                   Implements IFormatProvider.GetFormat
      ' Determine whether custom formatting object is requested.
      If formatType Is GetType(ICustomFormatter) Then
         Return Me
      Else
         Return Nothing
      End If
   End Function   

   ' Format number in binary (B), octal (O), or hexadecimal (H).
   Public Function Format(fmt As String, arg As Object, _
                          formatProvider As IFormatProvider) As String _
                   Implements ICustomFormatter.Format

     ' Handle format string.
      Dim base As Integer
      ' Handle null or empty format string, string with precision specifier.
      Dim thisFmt As String = String.Empty
      ' Extract first character of format string (precision specifiers
      ' are not supported by BinaryFormatter).
      If Not String.IsNullOrEmpty(fmt) Then
         thisFmt = CStr(IIf(fmt.Length > 1, fmt.Substring(0, 1), fmt))
      End If
         


      ' Get a byte array representing the numeric value.
      Dim bytes() As Byte
      If TypeOf(arg) Is SByte Then
         Dim byteString As String = CType(arg, SByte).ToString("X2")
         bytes = New Byte(0) { Byte.Parse(byteString, System.Globalization.NumberStyles.HexNumber ) }
      ElseIf TypeOf(arg) Is Byte Then
         bytes = New Byte(0) { CType(arg, Byte) }
      ElseIf TypeOf(arg) Is Int16 Then
         bytes = BitConverter.GetBytes(CType(arg, Int16))
      ElseIf TypeOf(arg) Is Int32 Then
         bytes = BitConverter.GetBytes(CType(arg, Int32))
      ElseIf TypeOf(arg) Is Int64 Then
         bytes = BitConverter.GetBytes(CType(arg, Int64))
      ElseIf TypeOf(arg) Is UInt16 Then
         bytes = BitConverter.GetBytes(CType(arg, UInt16))
      ElseIf TypeOf(arg) Is UInt32 Then
         bytes = BitConverter.GetBytes(CType(arg, UInt64))
      ElseIf TypeOf(arg) Is UInt64 Then
         bytes = BitConverter.GetBytes(CType(arg, UInt64))                  
      ElseIf TypeOf(arg) Is BigInteger Then
         bytes = CType(arg, BigInteger).ToByteArray()
      Else
         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

      Select Case thisFmt.ToUpper()
         ' Binary formatting.
         Case "B"
            base = 2        
         Case "O"
            base = 8
         Case "H"
            base = 16
         ' Handle unsupported format strings.
         Case Else
            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 Select
      
      ' Return a formatted string.
      Dim numericString As String = String.Empty
      For ctr As Integer = bytes.GetUpperBound(0) To bytes.GetLowerBound(0) Step -1
         Dim byteString As String = Convert.ToString(bytes(ctr), base)
         If base = 2 Then
            byteString = New String("0"c, 8 - byteString.Length) + byteString
         ElseIf base = 8 Then
            byteString = New String("0"c, 4 - byteString.Length) + byteString
         ' Base is 16.
         Else     
            byteString = New String("0"c, 2 - byteString.Length) + byteString
         End If
         numericString +=  byteString + " "
      Next
      Return numericString.Trim()
   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

BinaryFormatter接著, 可以藉由傳遞BinaryFormatter物件做為Format方法的provider參數, 來提供自訂格式, 如下列範例所示。BinaryFormatter can then be used to provide custom formatting by passing a BinaryFormatter object as the provider parameter of the Format method, as the following example shows.

public class Example
{
   public static void Main()
   {
      Console.WindowWidth = 100;
      
      byte byteValue = 124;
      Console.WriteLine(String.Format(new BinaryFormatter(), 
                                      "{0} (binary: {0:B}) (hex: {0:H})", byteValue));
      
      int intValue = 23045;
      Console.WriteLine(String.Format(new BinaryFormatter(), 
                                      "{0} (binary: {0:B}) (hex: {0:H})", intValue));
      
      ulong ulngValue = 31906574882;
      Console.WriteLine(String.Format(new BinaryFormatter(), 
                                      "{0}\n   (binary: {0:B})\n   (hex: {0:H})", 
                                      ulngValue));

      BigInteger bigIntValue = BigInteger.Multiply(Int64.MaxValue, 2);
      Console.WriteLine(String.Format(new BinaryFormatter(), 
                                      "{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)
Public Module Example
   Public Sub Main
      Console.WindowWidth = 100
      
      Dim byteValue As Byte = 124
      Console.WriteLine(String.Format(New BinaryFormatter(), _
                                      "{0} (binary: {0:B}) (hex: {0:H})", byteValue))
      
      Dim intValue As Integer = 23045
      Console.WriteLine(String.Format(New BinaryFormatter(), _
                                      "{0} (binary: {0:B}) (hex: {0:H})", intValue))
      
      Dim ulngValue As ULong = 31906574882
      Console.WriteLine(String.Format(New BinaryFormatter(), _
                                      "{0} {1}   (binary: {0:B}) {1}   (hex: {0:H})", _
                                      ulngValue, vbCrLf))

      Dim bigIntValue As BigInteger = BigInteger.Multiply(Int64.MaxValue, 2)
      Console.WriteLine(String.Format(New BinaryFormatter(), _
                                      "{0} {1}   (binary: {0:B}) {1}   (hex: {0:H})", _
                                      bigIntValue, vbCrLf))
   End Sub
End Module
' 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 是一種回呼方法。ICustomFormatter.Format is a callback method. 它是由支援自訂格式的方法所呼叫, 例如String.Format(IFormatProvider, String, Object[])StringBuilder.AppendFormat(IFormatProvider, String, Object[])It is called by a method that supports custom formatting, such as String.Format(IFormatProvider, String, Object[]) or StringBuilder.AppendFormat(IFormatProvider, String, Object[]). 會針對複合格式字串中的每個格式專案呼叫一次執行。The implementation is called once for each format item in a composite format string. 例如, 在下列語句中, ICustomFormatter.Format會呼叫方法三次。For example, in the following statement, the ICustomFormatter.Format method is called three times.

Console.WriteLine(String.Format(new BinaryFormatter(), 
                                "{0} (binary: {0:B}) (hex: {0:H})", byteValue));
Console.WriteLine(String.Format(New BinaryFormatter(), _
                                "{0} (binary: {0:B}) (hex: {0:H})", byteValue))

arg參數是物件清單中的物件, 其以零為基底的位置對應至特定格式專案的索引。The arg parameter is the object in the object list whose zero-based position corresponds to the index of a particular format item.

參數包含格式字串, 這formatString是格式專案的元件。 formatThe format parameter contains a format string, which is the formatString component of a format item. 如果格式專案沒有formatString元件, 則的format值會是nullIf the format item has no formatString component, the value of format is null. 如果formatnull ,arg視的類型而定, 您可以使用您選擇的預設格式規格。If format is null, depending on the type of arg, you may be able to use the default format specification of your choice.

參數是提供格式的arg實作為。IFormatProvider formatProviderThe formatProvider parameter is the IFormatProvider implementation that provides formatting for arg. 一般來說, 這是您ICustomFormatter的實作為實例。Typically, it is an instance of your ICustomFormatter implementation. 如果formatProvidernull, 請忽略該參數。If formatProvider is null, ignore that parameter.

您的Format方法執行必須包含下列功能, 才能讓 .NET Framework 提供不支援的格式。Your implementation of the Format method must include the following functionality so the .NET Framework can provide formatting you do not support. 如果您的格式方法不支援格式, 請判斷正在格式化IFormattable的物件是否會執行介面。If your format method does not support a format, determine whether the object being formatted implements the IFormattable interface. 如果存在, 請IFormattable.ToString叫用該介面的方法。If it does, invoke the IFormattable.ToString method of that interface. 否則, 請叫用Object.ToString基礎物件的預設方法。Otherwise, invoke the default Object.ToString method of the underlying object. 下列程式碼說明此模式。The following code illustrates this pattern.

if (arg is IFormattable) 
   return ((IFormattable)arg).ToString(format, CultureInfo.CurrentCulture);
else if (arg != null)
   return arg.ToString();
If TypeOf arg Is IFormattable Then
   Return DirectCast(arg, IFormattable).ToString(fmt, CultureInfo.CurrentCulture)
ElseIf arg IsNot Nothing Then
   Return arg.ToString()

適用於

另請參閱