IFormatProvider.GetFormat(Type) 方法
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
返回一个对象,该对象为指定类型提供格式设置服务。
public:
System::Object ^ GetFormat(Type ^ formatType);
public object GetFormat (Type formatType);
public object? GetFormat (Type? formatType);
abstract member GetFormat : Type -> obj
Public Function GetFormat (formatType As Type) As Object
参数
- formatType
- Type
一个对象,该对象指定要返回的格式对象的类型。
返回
如果 IFormatProvider 实现能够提供该类型的对象,则为 formatType
所指定对象的实例;否则为 null
。
示例
以下示例演示如何使用实现 接口和 GetFormat 方法的IFormatProvider类。 类 AcctNumberFormat
将 Int64 表示帐户号的值转换为格式化的 12 位帐户号。 如果 参数引用实现ICustomFormatter的类,则其 GetFormat
方法返回对自身的引用;否则返回 GetFormat
null
。formatType
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
然后, AcctNumberFormat
可以将 类的实例作为参数传递给提供格式设置或分析服务的方法。 例如,以下代码将 类 AcctNumberFormat
传递给 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.
注解
GetFormat 是一种回调方法,格式化和分析方法调用它来检索有关分析操作中输入字符串的格式或格式设置操作中输出字符串的格式的信息。
formatType
在 参数中,格式设置或分析方法传递执行其操作所需的对象类型。
IFormatProvider如果实现可以提供此格式设置或分析对象,它将返回该对象。 如果不是,则返回 null
。
例如,在调用 Int32.ToString(IFormatProvider) 方法时,方法参数是一个 IFormatProvider 对象,它提供有关如何设置当前整数实例的字符串表示形式的信息。 当运行时执行 方法时,它会调用 IFormatProvider 对象的 GetFormat 方法,并为其传递一个 Type 表示类型的 NumberFormatInfo 对象。
IFormatProvider如果对象可以提供对象NumberFormatInfo,则返回该对象。 如果它无法提供该类型的对象,则返回 null
。
可以在提供自定义格式设置或分析服务的类中实现 IFormatProvider 接口和 GetFormat 方法。 然后,该 IFormatProvider 实现作为参数传递给具有 类型 IFormatProvider参数(如 String.Format(IFormatProvider, String, Object[])、 Int32.ToString(String, IFormatProvider)或 DateTime.Parse(String, IFormatProvider))的解析或格式设置方法的任何重载。