IFormatProvider.GetFormat(Type) 메서드

정의

지정된 형식에 대한 형식 지정 서비스를 제공하는 개체를 반환합니다.

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

반환할 형식 개체의 형식을 지정하는 개체입니다.

반환

Object

IFormatProvider 구현에서 해당 형식의 개체를 제공할 수 있으면 formatType에 지정된 개체의 인스턴스이고, 그렇지 않으면 null입니다.

예제

다음 예제를 구현 하는 클래스를 사용 하 여 IFormatProvider 인터페이스 및 GetFormat 메서드. 합니다 AcctNumberFormat 변환 클래스는 Int64 12 자리 계정 형식이 지정 된 수는 계정 번호를 나타내는 값입니다. 해당 GetFormat 메서드는 경우 자체에 대 한 참조를 반환 합니다 formatType 매개 변수를 구현 하는 클래스를 참조 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

인스턴스는 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)합니다.

적용 대상