다음을 통해 공유


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

쉽게 사용할 수 있는 implicit 변환 연산자나 또는 변환한 타입의 코드를 읽는 사람에게 명확하게 나타나는 explicit 변환 연산자를 사용할 수 있습니다. 여기서 변환 연산자의 형식을 모두 보여줍니다.

예제

다음 코드는 명시적 변환 연산자의 예입니다. 이 연산자는 Byte 형식을 Digit라는 값 형식으로 변환합니다. 모든 바이트를 숫자로 변환할 수 있는 것은 아니므로 이 변환은 명시적입니다. 즉, Main 메서드에서와 같이 캐스트를 사용해야 합니다.

struct Digit
{
    byte value;

    public Digit(byte value)  //constructor
    {
        if (value > 9)
        {
            throw new System.ArgumentException();
        }
        this.value = value;
    }

    public static explicit operator Digit(byte b)  // explicit byte to digit conversion operator
    {
        Digit d = new Digit(b);  // explicit conversion

        System.Console.WriteLine("Conversion occurred.");
        return d;
    }
}

class TestExplicitConversion
{
    static void Main()
    {
        try
        {
            byte b = 3;
            Digit d = (Digit)b;  // explicit conversion
        }
        catch (System.Exception e)
        {
            System.Console.WriteLine("{0} Exception caught.", e);
        }
    }
}
// Output: Conversion occurred.

이 예제에서는 암시적 변환 연산자를 보여 줍니다. 이를 위해 이전 예제에서 수행한 작업을 실행 취소하는 변환 연산자를 정의합니다. 이 예제에서는 Digit이라는 값 클래스를 정수 계열 Byte 형식으로 변환합니다. 모든 숫자를 Byte로 변환할 수 있으므로 사용자에게 변환 사실을 명시적으로 알릴 필요가 없습니다.

struct Digit
{
    byte value;

    public Digit(byte value)  //constructor
    {
        if (value > 9)
        {
            throw new System.ArgumentException();
        }
        this.value = value;
    }

    public static implicit operator byte(Digit d)  // implicit digit to byte conversion operator
    {
        System.Console.WriteLine("conversion occurred");
        return d.value;  // implicit conversion
    }
}

class TestImplicitConversion
{
    static void Main()
    {
        Digit d = new Digit(3);
        byte b = d;  // implicit conversion -- no cast needed
    }
}
// Output: Conversion occurred.

참고 항목

참조

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

is(C# 참조)

개념

C# 프로그래밍 가이드

기타 리소스

C# 참조