2011-08-10 8 views
1

호출 된 다중 계층 클래스 시스템에 특정 함수가 있으며 함수가 호출 될 때 올바른 함수를 선택합니다. 특정 클래스의 함수를 선택하도록 지시하려면 어떻게합니까?올바른 함수를 호출하는 다형성

정답을 얻으려면 다른 어떤 정보가 필요한지 알려주십시오. 충분한 답변이 없거나 모호한 지 확실하지 않습니다. 내가 C#을 처음 접했을 때 제공해야 할 부분을 구체적으로 알려주십시오.

+0

여러 파견 같은데. –

+2

당신은'class A {}'class B : A {}''C : B {}'와 같은 상속 유산을 가지고 있고 instanceOfA.SomeMethod()를 호출하고 C.SomeMethod를 실행 시키길 원합니까? 이 경우 메서드를 가상으로 표시하려고합니다. 솔직히 질문은 이해하기 어렵습니다. – asawyer

+2

질문에 약간의 세부 사항을 추가 할 수 있습니까? 그것은'특정 함수'에 대한 코드를 가지고 도움이 될 것입니다 그리고 아마도 당신은 당신이 원하는 결과를 얻을 수 있도록 리펙터를 도울 수 있습니다. – Crisfole

답변

2

내가 생각할 수있는 다형성에 대한 가장 기본적인 예를 만들었습니다. 예문과 설명을 이해하려고하면보다 구체적인 질문이 있으면 게시판을 업데이트 할 것입니다.

첫 번째 코드 예제에는 두 개의 클래스가 포함되어 있으며 두 번째 코드는 다형성을 보여주기 위해이 클래스의 개체 메서드를 호출합니다. 이 같은 것을 사용

public class BaseClass 
{ 
    // This method can be "replaced" by classes which inherit this class 
    public virtual void OverrideableMethod() 
    { 
     System.Console.WriteLine("BaseClass.OverrideableMethod()"); 
    } 

    // This method is called when the type is of your variable is "BaseClass" 
    public void Method() 
    { 
     Console.WriteLine("BaseClass.Method()"); 
    } 
} 

public class SpecializedClass : BaseClass 
{ 

    // your specialized code 
    // the original method from BaseClasse is not accessible anymore 
    public override void OverrideableMethod() 
    { 
     Console.WriteLine("SpecializedClass.OverrideableMethod()"); 

     // call the base method if you need to 
     // base.OverrideableMethod(); 
    } 

    // this method hides the Base Classes code, but it still is accessible 
    // - without the "new" keyword the compiler generates a warning 
    // - try to avoid method hiding 
    // - it is called when the type is of your variable is "SpecializedClass" 
    public new void Method() 
    { 
     Console.WriteLine("SpecializedClass.Method()"); 
    } 
} 

테스트 클래스는 :

Console.WriteLine("testing base class"); 

BaseClass baseClass = new BaseClass(); 
baseClass.Method(); 
baseClass.OverrideableMethod(); 


Console.WriteLine("\n\ntesting specialized class"); 

SpecializedClass specializedClass = new SpecializedClass(); 
specializedClass.Method(); 
specializedClass.OverrideableMethod(); 


Console.WriteLine("\n\nuse specialized class as base class"); 

BaseClass containsSpecializedClass = specializedClass; 
containsSpecializedClass.Method(); 
containsSpecializedClass.OverrideableMethod(); 
+0

이것은 정확히 내가 필요로 한 것입니다. 고맙습니다. – user710502

관련 문제