IFormatProvider 인터페이스
정의
서식 지정을 제어하는 개체를 검색하기 위한 메커니즘을 제공합니다.Provides a mechanism for retrieving an object to control formatting.
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 구현에는 날짜 및 시간 값의 표현을 변경할 수 있습니다.The following example illustrates how an IFormatProvider implementation can change the representation of a date and time value. 하나의 날짜를 사용 하 여 표시 됩니다는 예제의 경우 CultureInfo 네 개의 서로 다른 문화권을 나타내는 개체입니다.In this case, a single date is displayed by using CultureInfo objects that represent four different cultures.
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
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
다음 예제를 구현 하는 클래스를 사용 하 여 IFormatProvider 인터페이스 및 GetFormat 메서드.The following example illustrates the use of a class that implements the IFormatProvider interface and the GetFormat method. 합니다 AcctNumberFormat
변환 클래스는 Int64 12 자리 계정 형식이 지정 된 수는 계정 번호를 나타내는 값입니다.The AcctNumberFormat
class converts an Int64 value that represents an account number to a formatted 12-digit account number. 해당 GetFormat
메서드는 현재에 대 한 참조를 반환 AcctNumberFormat
인스턴스를 formatType
매개 변수를 구현 하는 클래스를 참조 ICustomFormatter이 고, 그렇지 않으면 GetFormat
반환 null
합니다.Its GetFormat
method returns a reference to the current AcctNumberFormat
instance if the formatType
parameter refers to a class that implements ICustomFormatter; otherwise, GetFormat
returns 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;
}
}
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 를 서식 지정 및 구문 분석 작업에 대 한 호출에서 사용할 수 있습니다.The class that implements IFormatProvider can then be used in a call to a formatting and parsing operation. 예를 들어, 다음 코드 호출을 String.Format(IFormatProvider, String, Object[]) 서식이 지정 된 12 자리 계정 번호를 포함 하는 문자열을 생성 하는 방법입니다.For example, the following code calls the String.Format(IFormatProvider, String, Object[]) method to generate a string that contains a formatted 12-digit account number.
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.
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 인터페이스 서식 지정 및 구문 분석 작업에 대 한 서식 지정 정보를 제공 하는 개체를 제공 합니다.The IFormatProvider interface supplies an object that provides formatting information for formatting and parsing operations. 형식의 값 해당 값의 문자열 표현으로 변환 하는 서식 지정 작업입니다.Formatting operations convert the value of a type to the string representation of that value. 일반적인 서식 지정 메서드를 ToString
형식의 메서드 뿐만 Format합니다.Typical formatting methods are the ToString
methods of a type, as well as Format. 값의 문자열 표현을 해당 값을 가진 형식으로 변환 하는 구문 분석 작업 합니다.Parsing operations convert the string representation of a value to a type with that value. 일반적인 구문 분석 메서드는 Parse
고 TryParse
입니다.Typical parsing methods are Parse
and TryParse
.
합니다 IFormatProvider 인터페이스는 단일 메서드로 구성 IFormatProvider.GetFormat합니다.The IFormatProvider interface consists of a single method, IFormatProvider.GetFormat. GetFormat 콜백 메서드는: 구문 분석 또는 형식 지정 메서드 호출 및 전달는 Type 서식 지정 또는 구문 분석 방법 필요로 하는 개체의 형식을 나타내는 개체를 서식 지정 정보를 제공 합니다.GetFormat is a callback method: The parsing or formatting method calls it and passes it a Type object that represents the type of object that the formatting or parsing method expects will provide formatting information. GetFormat 메서드는 해당 형식의 개체를 반환 하는 일을 담당 합니다.The GetFormat method is responsible for returning an object of that type.
IFormatProvider 서식 지정 및 구문 분석 메서드 구현에서는 암시적으로 자주 사용 됩니다.IFormatProvider implementations are often used implicitly by formatting and parsing methods. 예를 들어, 합니다 DateTime.ToString(String) 메서드를 암시적으로 사용 하는 IFormatProvider 시스템의 현재 문화권을 나타내는 구현 합니다.For example, the DateTime.ToString(String) method implicitly uses an IFormatProvider implementation that represents the system's current culture. IFormatProvider 구현도 지정할 수 있습니다 명시적으로 형식 매개 변수가 있는 메서드에 의해 IFormatProvider와 같은 Int32.Parse(String, IFormatProvider) 고 String.Format(IFormatProvider, String, Object[])합니다.IFormatProvider implementations can also be specified explicitly by methods that have a parameter of type IFormatProvider, such as Int32.Parse(String, IFormatProvider) and String.Format(IFormatProvider, String, Object[]).
.NET Framework에 미리 정의 된 다음 세 가지 IFormatProvider 서식 지정 또는 숫자와 날짜 및 시간 값을 구문 분석에 사용 되는 문화권별 정보를 제공 하는 구현 합니다.The .NET Framework includes the following three predefined IFormatProvider implementations to provide culture-specific information that is used in formatting or parsing numeric and date and time values:
NumberFormatInfo 수천 대의 통화와 같은 숫자의 형식을 지정 하는 데 사용 되는 정보를 제공 하는 클래스 구분 기호 및 특정 문화권에 대 한 소수 구분 기호입니다.The NumberFormatInfo class, which provides information that is used to format numbers, such as the currency, thousands separator, and decimal separator symbols for a particular culture. 인식 되는 미리 정의 된 형식 문자열에 대 한 자세한를 NumberFormatInfo 개체 및 숫자 서식 지정 작업 사용을 참조 하세요 Standard Numeric Format Strings 고 Custom Numeric Format Strings.For information about the predefined format strings recognized by a NumberFormatInfo object and used in numeric formatting operations, see Standard Numeric Format Strings and Custom Numeric Format Strings.
DateTimeFormatInfo 날짜 및 시간이 같은 날짜 및 시간 구분 기호는 특정 문화권 또는 순서와 날짜의 연도, 월 및 일 구성 요소 형식의 서식을 지정 하는 데 사용 되는 정보를 제공 하는 클래스입니다.The DateTimeFormatInfo class, which provides information that is used to format dates and times, such as the date and time separator symbols for a particular culture or the order and format of a date's year, month, and day components. 인식 되는 미리 정의 된 형식 문자열에 대 한 자세한를 DateTimeFormatInfo 개체 및 숫자 서식 지정 작업 사용을 참조 하세요 표준 날짜 및 시간 형식 문자열 고 사용자 지정 날짜 및 시간 형식 문자열 .For information about the predefined format strings recognized by a DateTimeFormatInfo object and used in numeric formatting operations, see Standard Date and Time Format Strings and Custom Date and Time Format Strings.
CultureInfo 특정 문화권을 나타내는 클래스입니다.The CultureInfo class, which represents a particular culture. 해당 GetFormat 메서드는 문화권별 NumberFormatInfo 또는 DateTimeFormatInfo 인지에 따라 개체를 CultureInfo 를 서식 지정 또는 구문 분석 작업에서 숫자 또는 날짜 및 시간을 포함 하는 개체를 사용 합니다.Its GetFormat method returns a culture-specific NumberFormatInfo or DateTimeFormatInfo object, depending on whether the CultureInfo object is used in a formatting or parsing operation that involves numbers or dates and times.
.NET Framework는 또한 사용자 지정 서식 지정을 지원합니다.The .NET Framework also supports custom formatting. 이 둘 다 구현 하는 형식 지정 클래스를 만드는 일반적 IFormatProvider 고 ICustomFormatter입니다.This typically involves the creation of a formatting class that implements both IFormatProvider and ICustomFormatter. 이 클래스의 인스턴스는 같은 사용자 지정 작업을 수행 하는 메서드 매개 변수로 전달 다음 String.Format(IFormatProvider, String, Object[]) 예제에서는 12 자리 계정 번호를 숫자 형식을 지정 하는 이러한 사용자 지정 구현 보여 줍니다.An instance of this class is then passed as a parameter to a method that performs a custom formatting operation, such as String.Format(IFormatProvider, String, Object[]) The example provides an illustration of such a custom implementation that formats a number as a 12-digit account number.
메서드
GetFormat(Type) |
지정된 형식에 대한 형식 지정 서비스를 제공하는 개체를 반환합니다.Returns an object that provides formatting services for the specified type. |