Notice
Recent Posts
Recent Comments
Link
«   2024/07   »
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
Archives
Today
Total
07-08 04:38
관리 메뉴

nomad-programmer

[Programming/C#] 메소드 숨기기 본문

Programming/C#

[Programming/C#] 메소드 숨기기

scii 2020. 9. 9. 13:40

메소드 숨기기란, CLR에게 부모 클래스에서 구현된 버전의 메소드를 감추고 파생 클래스에서 구현된 버전만을 보여주는 것을 말한다. 
메소드 숨기기는 파생 클래스 버전의 메소드를 new 한정자로 수식함으로써 할 수 있다. (생성자를 호출할 때 사용하는 new 연산자와는 다르다)

메소드 숨기기는 오버라이딩과 다르다. 이름 그대로 메소드를 숨기고 있을 분이다.

메소드 숨기기는 완전한 다형성을 표현하지 못하는 한계를 갖고 있다. 따라서 부모 클래스를 설계할 때는 파생 클래스의 모습까지 고려해야 한다.

using System;

namespace CSharpExample
{
    class Base
    {
        public void MyMethod()
        {
            Console.WriteLine("Base.MyMethod()");
        }
    }

    class Derived : Base
    {
        public new void MyMethod()
        {
            Console.WriteLine("Derived.MyMethod()");
        }
    }

    class MainApp
    {

        static int Main(string[] args)
        {
            Base baseObj = new Base();
            baseObj.MyMethod();

            Derived derivedObj = new Derived();
            derivedObj.MyMethod();

            Base baseOrDerived = new Derived();
            baseOrDerived.MyMethod();

            return 0;
        }
    }
}

/* 결과

Base.MyMethod()
Derived.MyMethod()
Base.MyMethod()

*/
Comments