ICustomFormatter 介面

定義

定義可支援物件值之自訂格式的方法。Defines a method that supports custom formatting of the value of an object.

public interface class ICustomFormatter
public interface ICustomFormatter
[System.Runtime.InteropServices.ComVisible(true)]
public interface ICustomFormatter
type ICustomFormatter = interface
[<System.Runtime.InteropServices.ComVisible(true)>]
type ICustomFormatter = interface
Public Interface ICustomFormatter
屬性

範例

下列範例會執行, ICustomFormatter 以允許整數值的二進位、八進位和十六進位格式。The following example implements ICustomFormatter to allow binary, octal, and hexadecimal formatting of integral values. 在此範例中,單一類別,會 IBinaryFormatter 同時執行 ICustomFormatterIFormatProviderIn this example, a single class, IBinaryFormatter, implements both ICustomFormatter and IFormatProvider. IFormatProvider.GetFormat 的方法會判斷 formatType 參數是否代表 ICustomFormatter 型別。Its IFormatProvider.GetFormat method determines whether the formatType parameter represents an ICustomFormatter type. 如果有,則會傳回 BinaryFormatter 本身的實例,否則會傳回 nullIf it does, BinaryFormatter returns an instance of itself; otherwise, it returns null. ICustomFormatter.Format 實作為判斷格式參數是否為三個支援的格式字串之一 ( "B" 代表 binary,"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 ,方法是傳遞物件做 provider 為方法的參數 Format ,如下列範例所示。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介面包含單一方法 ICustomFormatter.FormatThe ICustomFormatter interface includes a single method, ICustomFormatter.Format. 當這個介面是由參考型別或實值型別所執行時,方法會傳回 Format 物件值的自訂格式字串表示。When this interface is implemented by a reference or value type, the Format method returns a custom-formatted string representation of an object's value.

通常 ICustomFormatter 會使用介面來執行介面, IFormatProvider 以自訂兩個 .NET Framework 複合字串格式化方法(包含參數)的行為 IFormatProviderTypically, the ICustomFormatter interface is implemented with the IFormatProvider interface to customize the behavior of two .NET Framework composite string formatting methods that include an IFormatProvider parameter. 具體而言, ICustomFormatter 介面可以針對傳遞給和方法的物件,提供其值的自訂格式 String.Format(IFormatProvider, String, Object[]) StringBuilder.AppendFormat(IFormatProvider, String, Object[])Specifically, the ICustomFormatter interface can provide custom formatting of the value of an object passed to the String.Format(IFormatProvider, String, Object[]) and StringBuilder.AppendFormat(IFormatProvider, String, Object[]) methods.

若要提供物件值的自訂表格示,您需要執行下列動作:Providing a custom representation of an object's value requires that you do the following:

  1. 定義一個類別,該類別會執行 ICustomFormatter 介面及其單一成員( Format 方法)。Define a class that implements the ICustomFormatter interface and its single member, the Format method.

  2. 定義一個類別,該類別會執行 IFormatProvider 介面及其單一成員( GetFormat 方法)。Define a class that implements the IFormatProvider interface and its single member, the GetFormat method. 方法會傳回 GetFormat 您的執行實例 ICustomFormatterThe GetFormat method returns an instance of your ICustomFormatter implementation. 通常,單一類別會同時執行 ICustomFormatterIFormatProviderOften, a single class implements both ICustomFormatter and IFormatProvider. 在此情況下,類別的 GetFormat 實只會傳回本身的實例。In that case, the class's GetFormat implementation just returns an instance of itself.

  3. 傳遞 IFormatProvider 實作為方法的 provider 引數 String.Format(IFormatProvider, String, Object[]) 或可比較的方法。Pass the IFormatProvider implementation as the provider argument of the String.Format(IFormatProvider, String, Object[]) method or a comparable method.

然後,.NET Framework 方法會使用您的自訂格式,而不是自己的格式。The .NET Framework method will then use your custom formatting instead of its own.

給實施者的注意事項

Common language runtime 會嘗試 ICustomFormatter 針對複合格式字串中的每個格式專案使用您的實作為。The common language runtime attempts to use your ICustomFormatter implementation for every format item in a composite format string. 如此一來,您應該會預期 ICustomFormatter 會呼叫您的實,以提供格式化服務給非設計來處理的物件或值。As a result, you should expect that your ICustomFormatter implementation will be called to provide formatting services to objects or values that it is not designed to handle. 在這些情況下,您的 Format(String, Object, IFormatProvider) 方法必須針對該物件或值呼叫適當的格式化方法。In these cases, your Format(String, Object, IFormatProvider) method must call the appropriate formatting method for that object or value.

有兩種類型的實作為:內建 ICustomFormatter 和延伸。There are two kinds of ICustomFormatter implementations: intrinsic and extension.

內建實作為提供應用程式定義物件之自訂格式的實作為。Intrinsic implementations are implementations that provide custom formatting for an application-defined object. 在此情況下,您的實應包含下列各項:In this case, your implementation should include the following: -定義物件格式的格式字串定義。- A definition of format strings that define the formatting of the object. 格式字串是選擇性的。Format strings are optional. 一般而言,"G" 或 "g" 格式字串會定義一般 (或最常使用的) 格式。Typically, a "G" or "g" format string defines the general (or most commonly used) format. 不過,您可以隨意定義任何您選擇的格式字串。However, you are free to define any format strings that you choose. 您也可以自行決定是否區分大小寫或不區分大小寫。You are also free to decide whether they are case-sensitive or case-insensitive.

-測試,以確保傳遞給方法的物件類型 Format(String, Object, IFormatProvider) 是您的應用程式定義型別。- A test to ensure that the type of the object passed to your Format(String, Object, IFormatProvider) method is your application-defined type. 如果不是,您應該呼叫物件的 IFormattable 執行(如果有的話)或其 ToString() 方法(如果沒有的話)。If it is not, you should call the object's IFormattable implementation, if one exists, or its ToString() method, if it does not. 您應該準備好處理這些方法呼叫可能會擲回的任何例外狀況。You should be prepared to handle any exceptions these method calls might throw.

-處理 null 格式字串的程式碼(如果您的實值支援格式字串)。- Code to handle a null format string, if your implementation supports format strings. 最常見的方法是使用一般格式規範來取代 null 格式字串。The most common approach is to replace a null format string with the general format specifier.

-程式碼,用來處理您的實作為支援的任何格式字串。- Code to handle any format strings that your implementation supports.

-程式碼,用來處理不支援的格式字串。- Code to handle format strings that you do not support. 最常見的方法是擲回 FormatException ,雖然您可以提供預設的格式設定。The most common approach is to throw a FormatException, although you can provide default formatting.

延伸模組的執行是針對已經有格式支援的型別,提供自訂格式的實作為。Extension implementations are implementations that provide custom formatting for a type that already has formatting support. 例如,您可以定義 CustomerNumberFormatter ,以在特定數位之間格式化具有連字號的整數型別。For example, you could define a CustomerNumberFormatter that formats an integral type with hyphens between specific digits. 在此情況下,您的實應包含下列各項:In this case, your implementation should include the following: -擴充物件格式的格式字串定義。- A definition of format strings that extend the formatting of the object. 這些格式字串是必要的,但它們不能與類型的現有格式字串衝突。These format strings are required, but they must not conflict with the type's existing format strings. 例如,如果您要擴充類型的格式設定 Int32 ,您不應該執行 "C"、"D"、"E"、"F" 和 "G" 格式規範,還有其他專案。For example, if you are extending formatting for the Int32 type, you should not implement the "C", "D", "E", "F", and "G" format specifiers, among others.

-測試:傳遞給方法的物件型別 Format(String, Object, IFormatProvider) 是您的延伸模組支援其格式的類型。- A test that the type of the object passed to your Format(String, Object, IFormatProvider) method is a type whose formatting your extension supports. 如果不是,請呼叫物件的 IFormattable 執行(如果有的話)或物件的無參數 ToString() 方法(如果沒有的話)。If it is not, call the object's IFormattable implementation, if one exists, or the object's parameterless ToString() method, if it does not. 您應該準備好處理這些方法呼叫可能會擲回的任何例外狀況。You should be prepared to handle any exceptions these method calls might throw.

-程式碼,用來處理您的延伸模組支援的任何格式字串。- Code to handle any format strings that your extension supports.

-程式碼,用來處理您的延伸模組不支援的任何格式字串。- Code to handle any format strings that your extension does not support. 這些應該傳遞至類型的 IFormattable 實作為。These should be passed on to the type's IFormattable implementation. 您應該準備好處理這些方法呼叫可能會擲回的任何例外狀況。You should be prepared to handle any exceptions these method calls might throw.

方法

Format(String, Object, IFormatProvider)

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

適用於

另請參閱