[C#] Interface

c# 2023. 1. 5. 17:23
728x90

MyEatFunc 에서는 매개변수로 받아온 obj를 IAnimal로 형변환 해준다

여기서 인터페이스를 상속받지않은 객체는 형변환에 실패하여 Eat 메서드가 수행되지 않는다(낙타)

즉 IAnimal을 상속받은 클래스ㅡ이 객체는 어떤 객체든 매개변수로 넣고 사용할 수 있다

이러한 과정을 인터페이를 통해 결합도를 낮췄다고 한다

class Program
    {
        static void Main(string[] args)
        {
            Person myPerson = new Person();
            Lion myLion = new Lion();
            Camel myCamel = new Camel();

            myPerson.Eat();
            myLion.Eat();
            myCamel.Eat();

            Console.WriteLine();

            MyEatFunc(myPerson);
            MyEatFunc(myLion);
            MyEatFunc(myCamel);
        }

        private static void MyEatFunc(object obj)
        {
            IAnimal target = obj as IAnimal;
            if (target != null)
            {
                target.Eat();
            }
        }
    }

    interface IAnimal
    {
        void Eat();
    }

    class Person : IAnimal
    {
        public void Eat()
        {
            Console.WriteLine("밥을 먹는다");
        }
    }

    class Lion : IAnimal
    {
        public void Eat()
        {
            Console.WriteLine("고기를 먹는다");
        }
    }

    class Camel
    {
        public void Eat()
        {
            Console.WriteLine("풀을 먹는다");
        }
    }
728x90

'c#' 카테고리의 다른 글

[C#] dynamic 동적 형식  (0) 2023.01.06
[C#] 덕타이핑과 dynamic  (0) 2023.01.06
[C#] 순수 함수  (0) 2023.01.04
[C#] 함수형 프로그래밍  (0) 2023.01.04
[C#] await 연산자  (0) 2023.01.04
Posted by 바르마스
,