다음을 통해 공유


IFormattable 인터페이스

개체 값을 문자열 표현으로 형식 지정하는 기능을 제공합니다.

네임스페이스: System
어셈블리: mscorlib(mscorlib.dll)

구문

‘선언
<ComVisibleAttribute(True)> _
Public Interface IFormattable
‘사용 방법
Dim instance As IFormattable
[ComVisibleAttribute(true)] 
public interface IFormattable
[ComVisibleAttribute(true)] 
public interface class IFormattable
/** @attribute ComVisibleAttribute(true) */ 
public interface IFormattable
ComVisibleAttribute(true) 
public interface IFormattable

설명

IFormattable은 기본 데이터 형식으로 구현됩니다.

형식은 개체를 문자열로 변환할 경우 개체의 모양을 설명합니다. 형식에는 표준 형식이나 사용자 지정 형식이 있을 수 있습니다. 표준 형식의 형태는 Axx인데, A는 형식 지정자라고 하는 영문자이고 xx는 전체 자릿수 지정자라고 하는 음수가 아닌 정수입니다. 형식 지정자는 문자열로 표현할 값에 지정되는 형식을 제어합니다. 전체 자릿수 지정자는 해당되는 경우 문자열의 유효 자릿수나 소수 자릿수를 제어합니다.

형식에 culture별로 다른 기호(예: "C" 및 "c" 형식으로 나타내는 통화 기호)가 포함될 경우 형식 지정 개체는 문자열 표현에 사용된 실제 문자를 제공합니다. 메서드에는 형식 지정 개체를 제공하는 IFormatProvider 개체를 전달하기 위한 매개 변수가 포함될 수 있습니다. 또는 메서드에서 현재 스레드에 대한 기호 정의를 포함하고 있는 기본 형식 지정 개체를 사용할 수도 있습니다. 일반적으로 현재 스레드에서는 시스템에서 기본적으로 사용하는 것과 동일한 기호 집합을 사용합니다.

구현자 참고 사항 Object.ToString에서 제공하는 것보다 문자열의 형식 지정을 더 잘 제어해야 하는 클래스에서 IFormattable를 구현해야하는데, 해당하는 ToString 메서드에서는 현재 스레드의 CurrentCulture 속성을 사용합니다. IFormattable를 구현하는 클래스에서는 "G"(일반) 형식 지정 코드를 지원해야 합니다. 클래스에서는 "G" 코드 외에 지원하는 형식 지정 코드 목록을 정의할 수 있습니다. 형식 지정 및 형식 지정 코드에 대한 자세한 내용은 형식 지정 개요를 참조하십시오.

예제

다음 예제에서는 IFormattable 인터페이스를 구현하는 형식을 정의하는 방법과 IFormattable 인터페이스의 ToString 메서드를 호출하는 방법을 보여 줍니다.

using System;

class Point : IFormattable
{
    public int x, y;

    public Point(int x, int y)
    {
        this.x = x;
        this.y = y;
    }

    public override String ToString() { return ToString(null, null); }

    public String ToString(String format, IFormatProvider fp)
    {
        // If no format is passed, display like this: (x, y).
        if (format == null) return String.Format("({0}, {1})", x, y);

        // For "x" formatting, return just the x value as a string
        if (format == "x") return x.ToString();

        // For "y" formatting, return just the y value as a string
        if (format == "y") return y.ToString();

        // For any unrecognized format, throw an exception.
        throw new FormatException(String.Format("Invalid format string: '{0}'.", format));
    }
}


public sealed class App
{
    static void Main()
    {
        // Create the object.
        Point p = new Point(5, 98);

        // Test ToString with no formatting.
        Console.WriteLine("This is my point: " + p.ToString());

        // Use custom formatting style "x"
        Console.WriteLine("The point's x value is {0:x}", p);

        // Use custom formatting style "y"
        Console.WriteLine("The point's y value is {0:y}", p);

        try 
        {
            // Use an invalid format; FormatException should be thrown here.
            Console.WriteLine("Invalid way to format a point: {0:XYZ}", p);
        }
        catch (FormatException e)
        {
            Console.WriteLine("The last line could not be displayed: {0}", e.Message);
        }
    }
}

// This code produces the following output.
// 
//  This is my point: (5, 98)
//  The point's x value is 5
//  The point's y value is 98
//  The last line could not be displayed: Invalid format string: 'XYZ'.
using namespace System;

public value struct Point : IFormattable
{
private:
    int x;

private:
    int y;

public:
    property int X
    {
        int get()
        {
            return x;
        }
        void set(int value)
        {
            x = value;
        }
    }

public:
    property int Y
    {
        int get()
        {
            return y;
        }
        void set(int value)
        {
            y = value;
        }
    }

public:
    Point(int x, int y)
    {
        this->x = x;
        this->y = y;
    }

public:
    virtual String^ ToString() override
    {
        return ToString(nullptr, nullptr);
    }

public:
    virtual String^ ToString(String^ format, IFormatProvider^ formatProvider)
    {
        // If no format is passed, display like this: (x, y).
        if (format == nullptr)
        {
            return String::Format("({0}, {1})", x, y);
        }

        // For "x" formatting, return just the x value as a string
        if (format == "x")
        {
            return x.ToString();
        }

        // For "y" formatting, return just the y value as a string
        if (format == "y")
        {
            return y.ToString();
        }

        // For any unrecognized format, throw an exception.
        throw gcnew FormatException(String::Format(
            "Invalid format string: '{0}'.", format));
    }
};

int main()
{
    // Create the object.
    Point p = Point(5, 98);

    // Test ToString with no formatting.
    Console::WriteLine("This is my point: " + p.ToString());

    // Use custom formatting style "x"
    Console::WriteLine("The point's x value is {0:x}", p);

    // Use custom formatting style "y"
    Console::WriteLine("The point's y value is {0:y}", p);

    try
    {
        // Use an invalid format;
        // FormatException should be thrown here.
        Console::WriteLine(
            "Invalid way to format a point: {0:XYZ}", p);
    }
    catch (FormatException^ e)
    {
        Console::WriteLine(
            "The last line could not be displayed: {0}",
            e->Message);
    }
}

// This code produces the following output.
//
//  This is my point: (5, 98)
//  The point's x value is 5
//  The point's y value is 98
//  The last line could not be displayed: Invalid format string: 'XYZ'.

플랫폼

Windows 98, Windows 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

.NET Framework에서 모든 플래폼의 모든 버전을 지원하지는 않습니다. 지원되는 버전의 목록은 시스템 요구 사항을 참조하십시오.

버전 정보

.NET Framework

2.0, 1.1, 1.0에서 지원

.NET Compact Framework

2.0, 1.0에서 지원

참고 항목

참조

IFormattable 멤버
System 네임스페이스
IFormatProvider 인터페이스
Object.ToString
CurrentCulture

기타 리소스

형식 지정 개요