ICustomFormatter 介面
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
定義一種支援物件值自訂格式的方法。
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 了整數值的二進位、八進位與十六進位格式化。 在此範例中,單一類別 MyFormatter, , 同時 ICustomFormatter 實作 與 IFormatProvider。 其 IFormatProvider.GetFormat 方法判斷參數 formatType 是否代表一種 ICustomFormatter 型別。 如果有,則 MyFormatter 回傳自己的一個實例;否則,回傳 null。 其 ICustomFormatter.Format 實作會判斷格式參數是否為三種支援的格式字串之一(「B」代表二進位,「O」代表八進位,「H」代表十六進位),並適當格式化參數 arg 。 否則,若arg不存在null,則呼叫參數的IFormattable.ToString實作(若存在),若不存在則呼叫arg無參數ToString方法。 若 arg , null則方法返回 String.Empty。
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;
}
}
open System
open System.Globalization
open System.Numerics
type MyFormatter() =
interface IFormatProvider with
// IFormatProvider.GetFormat implementation.
member this.GetFormat(formatType: Type) =
// Determine whether custom formatting object is requested.
if formatType = typeof<ICustomFormatter> then
this
else
null
interface ICustomFormatter with
// Format number in binary (B), octal (O), or hexadecimal (H).
member this.Format(format, arg: obj, formatProvider: IFormatProvider) =
// Handle null or empty format string, string with precision specifier.
let thisFmt =
// Extract first character of format string (precision specifiers
// are not supported).
if String.IsNullOrEmpty format |> not then
if format.Length > 1 then
format.Substring(0, 1)
else
format
else
String.Empty
// Get a byte array representing the numeric value.
let bytes =
match arg with
| :? sbyte as arg ->
let byteString = arg.ToString "X2"
Some [| Byte.Parse(byteString, NumberStyles.HexNumber) |]
| :? byte as arg ->
Some [| arg |]
| :? int16 as arg ->
BitConverter.GetBytes arg
|> Some
| :? int as arg ->
BitConverter.GetBytes arg
|> Some
| :? int64 as arg ->
BitConverter.GetBytes arg
|> Some
| :? uint16 as arg ->
BitConverter.GetBytes arg
|> Some
| :? uint as arg ->
BitConverter.GetBytes arg
|> Some
| :? uint64 as arg ->
BitConverter.GetBytes arg
|> Some
| :? bigint as arg ->
arg.ToByteArray()
|> Some
| _ ->
None
let baseNumber =
match thisFmt.ToUpper() with
// Binary formatting.
| "B" -> Some 2
| "O" -> Some 8
| "H" -> Some 16
// Handle unsupported format strings.
| _ -> None
match bytes, baseNumber with
| Some bytes, Some baseNumber ->
// Return a formatted string.
let mutable numericString = String.Empty
for i = bytes.GetUpperBound 0 to bytes.GetLowerBound 0 do
let byteString = Convert.ToString(bytes[i], baseNumber)
let byteString =
match baseNumber with
| 2 ->
String('0', 8 - byteString.Length) + byteString
| 8 ->
String('0', 4 - byteString.Length) + byteString
// Base is 16.
| _ ->
String('0', 2 - byteString.Length) + byteString
numericString <- numericString + byteString + " "
numericString.Trim()
| _ ->
try
this.HandleOtherFormats(format, arg)
with :? FormatException as e ->
raise (FormatException($"The format of '{format}' is invalid.", e))
member private this.HandleOtherFormats(format, arg: obj) =
match arg with
| :? IFormattable as arg ->
arg.ToString(format, CultureInfo.CurrentCulture)
| null ->
String.Empty
| _ ->
string arg
Imports System.Globalization
Imports System.Numerics
Public Class MyFormatter : 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 MyFormatter).
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
MyFormatter接著可以透過將物件作為provider方法的Format參數傳遞MyFormatter來提供自訂格式,如下範例所示。
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)
Console.WindowWidth <- 100
let byteValue = 124uy
String.Format(MyFormatter(), "{0} (binary: {0:B}) (hex: {0:H})", byteValue)
|> printfn "%s"
let intValue = 23045
String.Format(MyFormatter(), "{0} (binary: {0:B}) (hex: {0:H})", intValue)
|> printfn "%s"
let ulngValue = 31906574882uL
String.Format(MyFormatter(), "{0}\n (binary: {0:B})\n (hex: {0:H})", ulngValue)
|> printfn "%s"
let bigIntValue = BigInteger.Multiply(Int64.MaxValue, 2)
String.Format(MyFormatter(), "{0}\n (binary: {0:B})\n (hex: {0:H})", bigIntValue)
|> printfn "%s"
// 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 MyFormatter(), _
"{0} (binary: {0:B}) (hex: {0:H})", byteValue))
Dim intValue As Integer = 23045
Console.WriteLine(String.Format(New MyFormatter(), _
"{0} (binary: {0:B}) (hex: {0:H})", intValue))
Dim ulngValue As ULong = 31906574882
Console.WriteLine(String.Format(New MyFormatter(), _
"{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 MyFormatter(), _
"{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.Format。 當此介面由參考型別或值型別實作時,方法 Format 會回傳一個自訂格式化的字串表示物件值。
通常,ICustomFormatter 介面會透過 IFormatProvider 介面實作,以自訂兩種包含 IFormatProvider 參數的 .NET Framework 複合字串格式化方法的行為。 具體來說,介面 ICustomFormatter 可以提供傳遞給 String.Format(IFormatProvider, String, Object[]) and StringBuilder.AppendFormat(IFormatProvider, String, Object[]) 方法的物件值自訂格式。
提供物件值的自訂表示需要你做以下幾件事:
定義一個實 ICustomFormatter 作介面及其單一成員(方法) Format 的類別。
定義一個實 IFormatProvider 作介面及其單一成員(方法) GetFormat 的類別。 該 GetFormat 方法會回傳你的 ICustomFormatter 實作實例。 通常,一個類別同時 ICustomFormatter 實作 和 IFormatProvider。 在這種情況下,該類別
GetFormat的實作只是回傳一個自己的實例。將實作作為
provider方法或類似方法的參數String.Format(IFormatProvider, String, Object[])傳遞IFormatProvider。
.NET 函式庫的方法就會使用你自訂的格式,而不是它自己的格式。
給實施者的注意事項
通用語言執行時嘗試對複合格式字串中的每個格式項目使用你的 ICustomFormatter 實作。 因此,你應該預期你的 ICustomFormatter 實作會被呼叫,為它原本無法處理的物件或值提供格式化服務。 在這些情況下,你的 Format(String, Object, IFormatProvider) 方法必須呼叫該物件或值的適當格式化方法。
實作有兩種: ICustomFormatter 內在實作與擴展實作。
內在實作是為應用程式定義物件提供自訂格式的實作。 在這種情況下,你的實作應該包含以下內容:
定義了定義物件格式的格式字串。 格式字串為可選。 通常,「G」或「g」格式字串定義了一般(或最常用)的格式。 不過,你可以自由定義任何你選擇的格式字串。 你也可以自由決定它們是區分大小寫還是不區分大小寫。
一個測試,用來確保傳給你 Format(String, Object, IFormatProvider) 方法的物件型別是你應用程式定義的型別。 如果沒有,你應該呼叫物件的 IFormattable 實作(如果存在)或 ToString() 其方法(如果沒有)。 你應該準備好處理這些方法呼叫可能拋出的任何例外。
如果你的實作支援格式字串,可以寫程式碼處理空格式字串。 最常見的方法是將空格式字串替換為通用格式指定符。
程式碼來處理你的實作支援的任何格式字串。
程式碼來處理你不支援的格式字串。 最常見的方法是拋出 FormatException,雖然你也可以提供預設格式。
擴充實作是為已支援格式化的型別提供自訂格式的實作。 例如,你可以定義 CustomerNumberFormatter 一個,將積分型態格式化,並在特定數字間加連字號。 在這種情況下,你的實作應該包含以下內容:
一個格式字串的定義,用來擴展物件的格式化。 這些格式字串是必要的,但不得與該型別現有的格式字串衝突。 例如,如果你要擴充該類型的格式 Int32 ,就不應該實作「C」、「D」、「E」、「F」和「G」格式指定符等。
測試是,傳給你 Format(String, Object, IFormatProvider) 方法的物件類型是否符合你的擴充功能所支援的格式。 如果沒有,則呼叫該物件的 IFormattable 實作(若存在);若無參數方法存在,則呼叫該物件的無 ToString() 參數方法。 你應該準備好處理這些方法呼叫可能拋出的任何例外。
程式碼來處理你擴充功能支援的任何格式字串。
寫程式碼處理你的擴充套件不支援的任何格式字串。 這些資料應該交給該類型的 IFormattable 實作。 你應該準備好處理這些方法呼叫可能拋出的任何例外。
方法
| 名稱 | Description |
|---|---|
| Format(String, Object, IFormatProvider) |
利用指定的格式及文化特定格式資訊,將指定物件的值轉換為等效的字串表示。 |