C# 사용자 정의 형변환 - explicit, implicit



 두 기능 모두 C#4.0부터 지원해주고 있는 기능입니다.

explicit
 명시적 사용자 정의 형변화 연산자.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
class Celsius
{
    private float degress;
 
public Celsius(float degress)
    {
        this.degress = degress;
    }
    //Celsius -> Fahrenheit 명시적 형변환.
    public static explicit operator Fahrenheit(Celsius c)
    {
        return new Fahrenheit((9.0f / 5.0f) * c.degress + 32);
    }
    public float Degress
    {
        get { return this.degress; }
    }
}
 
class Fahrenheit
{
    private float degress;
 
    public Fahrenheit(float degress)
    {
        this.degress = degress;
    }
    //Fahrenheit -> Celsius 명시적 형변환.
    public static explicit operator Celsius(Fahrenheit fahr)
    {
        return new Celsius((5.0f / 9.0f) * (fahr.degress - 32));
    }
    public float Degress
    {
        get { return degress; }
    }
}
 
class TextExplicit
{
    static void Main()
    {
        Fahrenheit fahr = new Fahrenheit(100.0f);
        Celsius c = (Celsius)fahr; // Fahrenheit -> Celsius explicit conversion.
 
        Fahrenheit fahr2 = (Fahrenheit)c; //Celsius -> Fahrenheit explicit conversion.
    }
}



- implicit
 암시적 사용자 정의 형변화 연산자.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Digit
{
    byte value;
 
    public Digit(byte value)
    {
        if (value > 9)
        {
            throw new System.ArgumentException();
        }
        this.value = value;
    }
    // byte -> Digit 암시적 형변환.
    public static implicit operator Digit(byte b)
    { 
        return new Digit(b);
    }
    // Digit -> byte 암시적 형변환.
    public static implicit operator byte(Digit d)
    {
        return d.value;
    }
}
 
class TextImplicit
{
    static void Main()
    {
        Digit d = new Digit(3);
        byte b = d; // Digit -> byte implicit conversion.
 
        Digit dig2 = b; // byte -> Digit implicit conversion.
    }
}






참 고 : https://docs.microsoft.com/ko-kr/dotnet/csharp/programming-guide/statements-expressions-operators/using-conversion-operators

+ Recent posts