简体   繁体   English

以下继承之间有什么区别

[英]what is the difference between the following Inheritance

Here is the simple 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());
}

The above implementation will print Draw from Childclass 上面的实现将打印Childclass中的Draw

Here is the usage with the override 这是覆盖的用法

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

The above implementation will print Draw from Childclass 上面的实现将打印Childclass中的Draw

So what is the difference between above 2 Inheritance Implementation. 那么上述2继承实现之间有什么区别。

In the second snippet Draw is declared to be virtual, this means that you can call the inherited method from a variable of type BaseClass . 在第二个片段中,Draw被声明为虚拟的,这意味着您可以从BaseClass类型的变量中调用继承的方法。

BaseClass b = new ChildClass ();

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

Documentation 文献资料

Funny thing.. the second link in the list above uses the same snippets as you've provided. 有趣的是..上面列表中的第二个链接使用的片段与您提供的片段相同。

In the first implementation, if you call Draw() from inside BaseClass , the output will be "Draw from Base Class". 在第一个实现中,如果您从BaseClass内部调用Draw() ,则输出将为“ Draw from Base Class”。 But in the second implementation it will be "Draw from Child Class". 但是在第二个实现中,它将是“从子类中绘制”。 Here is an explanation: http://weblogs.sqlteam.com/mladenp/archive/2007/04/09/60168.aspx 这是一个解释: 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