explicit(C# 참조)

업데이트: 2007년 11월

explicit 키워드는 캐스트를 통해 호출해야 할 사용자 정의 형식 변환 연산자를 선언합니다. 예를 들어, 다음 연산자는 Fahrenheit라는 클래스를 Celsius라는 클래스로 변환합니다.

// Must be defined inside a class called Farenheit:
public static explicit operator Celsius(Fahrenheit f)
{
    return new Celsius((5.0f / 9.0f) * (f.degrees - 32));
}

이 변환 연산자는 다음과 같이 호출할 수 있습니다.

Fahrenheit f = new Fahrenheit(100.0f);
Console.Write("{0} fahrenheit", f.Degrees);
Celsius c = (Celsius)f;

변환 연산자는 소스 형식을 대상 형식으로 변환합니다. 소스 형식에서 변환 연산자를 제공합니다. 암시적 변환과 달리 명시적 변환은 캐스트를 통해 호출해야 합니다. 변환 연산으로 예외가 발생하거나 정보가 손실될 수 있는 경우 변환 연산을 explicit로 표시해야 합니다. 이렇게 해야 컴파일러가 예상치 않은 순서로 변환 연산을 호출하지 않습니다.

캐스트를 생략하면 컴파일 타임 오류 컴파일러 오류 CS0266이 발생합니다.

자세한 내용은 변환 연산자 사용(C# 프로그래밍 가이드)을 참조하십시오.

예제

다음 예제에서는 Fahrenheit 및 Celsius 클래스를 제공합니다. 각 클래스는 다른 클래스에 대한 명시적 변환 연산자를 제공합니다.

class Celsius
{
    public Celsius(float temp)
    {
        degrees = temp;
    }
    public static explicit operator Fahrenheit(Celsius c)
    {
        return new Fahrenheit((9.0f / 5.0f) * c.degrees + 32);
    }
    public float Degrees
    {
        get { return degrees; }
    }
    private float degrees;
}

class Fahrenheit
{
    public Fahrenheit(float temp)
    {
        degrees = temp;
    }
    // Must be defined inside a class called Farenheit:
    public static explicit operator Celsius(Fahrenheit f)
    {
        return new Celsius((5.0f / 9.0f) * (f.degrees - 32));
    }
    public float Degrees
    {
        get { return degrees; }
    }
    private float degrees;
}

class MainClass
{
    static void Main()
    {
        Fahrenheit f = new Fahrenheit(100.0f);
        Console.Write("{0} fahrenheit", f.Degrees);
        Celsius c = (Celsius)f;

        Console.Write(" = {0} celsius", c.Degrees);
        Fahrenheit f2 = (Fahrenheit)c;
        Console.WriteLine(" = {0} fahrenheit", f2.Degrees);
    }
}
/*
Output:
100 fahrenheit = 37.77778 celsius = 100 fahrenheit
*/

아래 예제에서는 단일 10 진수를 나타내는 Digit 구조체를 정의합니다. byte를 Digit로 변환하는 연산자가 정의되어 있지만 모든 바이트를 Digit로 변환할 수 있는 것은 아니므로 이 변환은 명시적입니다.

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

    // Define explicit byte-to-Digit conversion operator:
    public static explicit operator Digit(byte b)
    {
        Digit d = new Digit(b);
        Console.WriteLine("conversion occurred");
        return d;
    }
}

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

C# 언어 사양

자세한 내용은 C# 언어 사양의 다음 단원을 참조하십시오.

  • 6.2 명시적 변환

참고 항목

작업

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

개념

C# 프로그래밍 가이드

참조

C# 키워드

implicit(C# 참조)

operator(C# 참조)

기타 리소스

C# 참조

Chained user-defined explicit conversions in C#