다음을 통해 공유


방법: 구조체 간의 사용자 정의 변환 구현(C# 프로그래밍 가이드)

다음은 RomanNumeral과 BinaryNumeral의 두 구조체를 정의하고 이 두 구조체 간의 변환을 보여 주는 예제입니다.

예제

struct RomanNumeral
{
    private int value;

    public RomanNumeral(int value)  //constructor
    {
        this.value = value;
    }

    static public implicit operator RomanNumeral(int value)
    {
        return new RomanNumeral(value);
    }

    static public implicit operator RomanNumeral(BinaryNumeral binary)
    {
        return new RomanNumeral((int)binary);
    }

    static public explicit operator int(RomanNumeral roman)
    {
        return roman.value;
    }

    static public implicit operator string(RomanNumeral roman)
    {
        return ("Conversion to string is not implemented");
    }
}

struct BinaryNumeral
{
    private int value;

    public BinaryNumeral(int value)  //constructor
    {
        this.value = value;
    }

    static public implicit operator BinaryNumeral(int value)
    {
        return new BinaryNumeral(value);
    }

    static public explicit operator int(BinaryNumeral binary)
    {
        return (binary.value);
    }

    static public implicit operator string(BinaryNumeral binary)
    {
        return ("Conversion to string is not implemented");
    }
}

class TestConversions
{
    static void Main()
    {
        RomanNumeral roman;
        BinaryNumeral binary;

        roman = 10;

        // Perform a conversion from a RomanNumeral to a BinaryNumeral:
        binary = (BinaryNumeral)(int)roman;

        // Perform a conversion from a BinaryNumeral to a RomanNumeral: 
        // No cast is required:
        roman = binary;

        System.Console.WriteLine((int)binary);
        System.Console.WriteLine(binary);

        // Keep the console window open in debug mode.
        System.Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
    }
}
/* Output:
    10
    Conversion not yet implemented
*/

강력한 프로그래밍

  • 앞의 예제에 있는 다음 문을 살펴 봅니다.

    binary = (BinaryNumeral)(int)roman;
    

    이 문에서는 RomanNumeral을 BinaryNumeral로 변환합니다. RomanNumeral에서 BinaryNumeral로 직접 변환되지 않으므로 캐스트를 사용하여 RomanNumeral에서 int로 변환하고 또 다른 캐스트를 사용하여 int에서 BinaryNumeral로 변환합니다.

  • 또한 다음 문을 살펴 봅니다.

    roman = binary;
    

    이 문에서는 BinaryNumeral을 RomanNumeral로 변환합니다. RomanNumeral은 BinaryNumeral로부터의 암시적 변환을 정의하므로 캐스트가 필요하지 않습니다.

참고 항목

참조

변환 연산자(C# 프로그래밍 가이드)

개념

C# 프로그래밍 가이드

기타 리소스

C# 참조