2011-12-14 76 views
0

這裏的區別是簡單的繼承就是下面的繼承

public class BaseClass 
{ 
    public string Draw() 
    { 
     return "Draw from BaseClass"; 
    } 
} 

public class ChildClass:BaseClass 
{ 
    public string Draw() 
    { 
     return "Draw from ChildClass"; 
    } 
} 

static void Main(string[] args) 
{ 
    ChildClass c = new ChildClass(); 
    console.writeline(c.Draw()); 
} 

上述實施將打印 借鑑Childclass

這裏與覆蓋

public class BaseClass 
{ 
    public virtual string Draw() 
    { 
     return "Draw from BaseClass"; 
    } 
} 

public class ChildClass:BaseClass 
{ 
    public override string Draw() 
    { 
     return "Draw from ChildClass"; 
    } 
} 

static void Main(string[] args) 
{ 
    ChildClass c = new ChildClass(); 
    console.writeline(c.Draw()); 
} 

使用以上實現將打印 從子類中抽取

那麼上面的2繼承實現有什麼區別。

回答

3

在第二個片段中Draw被聲明爲虛擬的,這意味着您可以從類型爲BaseClass的變量中調用繼承的方法。

BaseClass b = new ChildClass(); 

b.Draw() // will call ChildClass.Draw 

文檔

有趣的事情。在列表中的第二個以上鍊接使用相同的代碼片段如你提供。

+2

值得一提的是,第一個片段被稱爲'方法隱藏',並且編譯器在使用方法隱藏而不使用new關鍵字時會生成CS0108警告。 – 2011-12-14 15:20:01