IFormatProvider 介面
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
提供機制來擷取要控制格式的物件。
public interface class IFormatProvider
public interface IFormatProvider
[System.Runtime.InteropServices.ComVisible(true)]
public interface IFormatProvider
type IFormatProvider = interface
[<System.Runtime.InteropServices.ComVisible(true)>]
type IFormatProvider = interface
Public Interface IFormatProvider
- 衍生
- 屬性
範例
下列範例說明實作如何 IFormatProvider 變更日期和時間值的標記法。 在此情況下,會使用 CultureInfo 代表四個不同文化特性的物件來顯示單一日期。
using System;
using System.Globalization;
public class Example
{
public static void Main()
{
DateTime dateValue = new DateTime(2009, 6, 1, 16, 37, 0);
CultureInfo[] cultures = { new CultureInfo("en-US"),
new CultureInfo("fr-FR"),
new CultureInfo("it-IT"),
new CultureInfo("de-DE") };
foreach (CultureInfo culture in cultures)
Console.WriteLine("{0}: {1}", culture.Name, dateValue.ToString(culture));
}
}
// The example displays the following output:
// en-US: 6/1/2009 4:37:00 PM
// fr-FR: 01/06/2009 16:37:00
// it-IT: 01/06/2009 16.37.00
// de-DE: 01.06.2009 16:37:00
open System
open System.Globalization
let dateValue = DateTime(2009, 6, 1, 16, 37, 0)
let cultures =
[ CultureInfo "en-US"
CultureInfo "fr-FR"
CultureInfo "it-IT"
CultureInfo "de-DE" ]
for culture in cultures do
printfn $"{culture.Name}: {dateValue.ToString culture}"
// The example displays the following output:
// en-US: 6/1/2009 4:37:00 PM
// fr-FR: 01/06/2009 16:37:00
// it-IT: 01/06/2009 16.37.00
// de-DE: 01.06.2009 16:37:00
Imports System.Globalization
Module Example
Public Sub Main()
Dim dateValue As Date = #06/01/2009 4:37PM#
Dim cultures() As CultureInfo = {New CultureInfo("en-US"), _
New CultureInfo("fr-FR"), _
New CultureInfo("it-IT"), _
New CultureInfo("de-DE") }
For Each culture As CultureInfo In cultures
Console.WriteLine("{0}: {1}", culture.Name, dateValue.ToString(culture))
Next
End Sub
End Module
' The example displays the following output:
' en-US: 6/1/2009 4:37:00 PM
' fr-FR: 01/06/2009 16:37:00
' it-IT: 01/06/2009 16.37.00
' de-DE: 01.06.2009 16:37:00
下列範例說明如何使用實作 介面和 方法的 GetFormat 類別 IFormatProvider 。 類別 AcctNumberFormat
會將 Int64 代表帳戶號碼的值轉換為格式化的 12 位數帳戶號碼。 如果 formatType
參數參考實作 的類別,其 GetFormat
方法會傳回目前 AcctNumberFormat
實例的 ICustomFormatter 參考,否則會 GetFormat
傳 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;
}
}
open System
open System.Globalization
type AcctNumberFormat() =
let [<Literal>] ACCT_LENGTH = 12
interface IFormatProvider with
member this.GetFormat(formatType: Type) =
if formatType = typeof<ICustomFormatter> then
this
else
null
interface ICustomFormatter with
member this.Format(fmt: string, arg: obj, formatProvider: IFormatProvider) =
// Provide default formatting if arg is not an Int64.
// Provide default formatting for unsupported format strings.
let ufmt = fmt.ToUpper CultureInfo.InvariantCulture
if arg.GetType() = typeof<Int64> && (ufmt = "H" || ufmt = "I") then
// Convert argument to a string.
let result = string arg
let result =
// If account number is less than 12 characters, pad with leading zeroes.
if result.Length < ACCT_LENGTH then
result.PadLeft(ACCT_LENGTH, '0')
else result
let result =
// If account number is more than 12 characters, truncate to 12 characters.
if result.Length > ACCT_LENGTH then
result.Substring(0, ACCT_LENGTH)
else result
// Integer-only format.
if ufmt = "I" then
result
// Add hyphens for H format specifier.
else // Hyphenated format.
result.Substring(0, 5) + "-" + result.Substring(5, 3) + "-" + result.Substring(8)
else
try
this.HandleOtherFormats(fmt, arg)
with :? FormatException as e ->
raise (FormatException($"The format of '{fmt}' is invalid.", e))
member _.HandleOtherFormats(format: string, arg: obj) =
match arg with
| :? IFormattable as arg ->
arg.ToString(format, CultureInfo.CurrentCulture)
| null ->
string arg
| _ ->
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
接著,實作 的 IFormatProvider 類別可以用於對格式化和剖析作業的呼叫。 例如,下列程式碼會呼叫 String.Format(IFormatProvider, String, Object[]) 方法,以產生包含格式化 12 位數帳戶號碼的字串。
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.
open System
open System.Globalization
type DaysOfWeek = Monday = 1 | Tuesday = 2
[<EntryPoint>]
let main _ =
let acctNumber = 104254567890L
let balance = 16.34
let wday = DaysOfWeek.Monday
let output =
String.Format(AcctNumberFormat(),
"On {2}, the balance of account {0:H} was {1:C2}.",
acctNumber, balance, wday)
printfn $"{output}"
let wday = DaysOfWeek.Tuesday
let output =
String.Format(AcctNumberFormat(),
"On {2}, the balance of account {0:I} was {1:C2}.",
acctNumber, balance, wday)
printfn $"{output}"
0
// 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.
備註
介面 IFormatProvider 會提供 物件,提供格式化和剖析作業的格式資訊。 格式化作業會將類型的值轉換為該值的字串表示。 一般格式方法是 ToString
型別的方法,以及 Format 。 剖析作業會將值的字串表示轉換為具有該值的類型。 典型的剖析方法是 Parse
和 TryParse
。
IFormatProvider介面是由單一方法 IFormatProvider.GetFormat 所組成。 GetFormat 是回呼方法:剖析或格式化方法會呼叫它,並傳遞 Type 物件,該物件代表格式設定或剖析方法預期的物件類型會提供格式資訊。 方法 GetFormat 負責傳回該型別的物件。
IFormatProvider 實作通常是透過格式化和剖析方法來隱含使用。 例如, DateTime.ToString(String) 方法會隱含地使用 IFormatProvider 表示系統目前文化特性的 實作。 IFormatProvider 實作也可以由具有 型 IFormatProvider 別 參數的方法明確指定,例如 Int32.Parse(String, IFormatProvider) 和 String.Format(IFormatProvider, String, Object[]) 。
.NET Framework包含下列三個預先定義的 IFormatProvider 實作,以提供用於格式化或剖析數值和日期和時間值的文化特性特定資訊:
類別 NumberFormatInfo ,提供用來格式化數位的資訊,例如特定文化特性的貨幣、千位分隔符號和小數分隔符號符號。 如需 物件所辨識 NumberFormatInfo 並用於數值格式作業之預先定義格式字串的資訊,請參閱 標準數值格式字串 和 自訂數值格式字串。
類別 DateTimeFormatInfo ,提供用來格式化日期和時間的資訊,例如特定文化特性的日期和時間分隔符號符號,或是日期年份、月和日元件的順序和格式。 如需物件所辨識 DateTimeFormatInfo 並用於數值格式作業之預先定義格式字串的資訊,請參閱 標準日期和時間格式字串 和 自訂日期和時間格式字串。
類別 CultureInfo ,表示特定文化特性。 其 GetFormat 方法會傳回特定文化特性 NumberFormatInfo 或 DateTimeFormatInfo 物件,視物件是 CultureInfo 用於包含數位或日期和時間的格式設定或剖析作業而定。
.NET Framework也支援自訂格式設定。 這通常牽涉到建立實作 和 ICustomFormatter 的格式類別 IFormatProvider 。 接著,這個類別的實例會當做參數傳遞至執行自訂格式設定作業的方法,例如 String.Format(IFormatProvider, String, Object[]) 此範例提供這類自訂實作的圖例,將數位格式化為 12 位數的帳戶號碼。
方法
GetFormat(Type) |
傳回物件,這個物件為所指定型別提供格式化服務。 |