2011-08-10 96 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