簡體   English   中英

以下繼承之間有什么區別

[英]what is the difference between the following Inheritance

這是簡單的繼承

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中的Draw

這是覆蓋的用法

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());
}

上面的實現將打印Childclass中的Draw

那么上述2繼承實現之間有什么區別。

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

BaseClass b = new ChildClass ();

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

文獻資料

有趣的是..上面列表中的第二個鏈接使用的片段與您提供的片段相同。

在第一個實現中,如果您從BaseClass內部調用Draw() ,則輸出將為“ Draw from Base Class”。 但是在第二個實現中,它將是“從子類中繪制”。 這是一個解釋: http : //weblogs.sqlteam.com/mladenp/archive/2007/04/09/60168.aspx

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM