[C# 객체지향] 다형성_클래스 간의 형 변환

eunjin lee·2022년 6월 22일
0

C# 9.0 프로그래밍

목록 보기
8/50

클래스 간 형 변환 시 특정 동작 혹은 연산을 하게 할 수 있다.
이 때 형 변환을 암시적으로 가능하게 하려면 implcit 연산자를, 명시적으로만 가능하게 하려면 explicit 연산자를 사용한다.



1. implicit 연산자

✍ 샘플 코드

    class Program
    {
        static void Main(string[] args)
        {
            Dollar dollar = new Dollar(1);
            Won won = dollar;
            Console.WriteLine(won);
        }
    }

    class Money
    {
        public decimal money;
        public Money(decimal money)
        {
            this.money = money;
        }
    }

    class Won : Money
    {
        public Won(decimal money) : base(money)
        {

        }
        public override string ToString()
        {
            return base.money + " Won";
        }

    }

    class Dollar : Money
    {
        public Dollar(decimal money) : base(money)
        {

        }
        public override string ToString()
        {
            return base.money + " Dollar";
        }

        static public implicit operator Won(Dollar dollar)
        {
            return new Won(dollar.money*1100);
        }
    }

✅ 결과

1100 Won

2. Explicit 연산자

✍ 샘플 코드

    class Program
    {
        static void Main(string[] args)
        {
            Dollar dollar = new Dollar(1);
            Won won = (Won) dollar;
            Console.WriteLine(won);
        }
    }
    
    class Dollar : Money
    {
		//생략
        static public explicit operator Won(Dollar dollar)
        {
            return new Won(dollar.money*1100);
        }
    }

✅ 결과

1100 Won

0개의 댓글