以下继承有什么区别

发布于 2024-12-21 08:03:24 字数 847 浏览 1 评论 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());
}

上面的实现将打印 Draw from 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());
}

上面的实现将打印 Draw from Childclass

那么上面2种继承实现有什么区别呢。

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

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

So what is the difference between above 2 Inheritance Implementation.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

俯瞰星空 2024-12-28 08:03:24

在第二个片段中,Draw 被声明为虚拟的,这意味着您可以从 BaseClass 类型的变量调用继承的方法。

BaseClass b = new ChildClass ();

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

文档

有趣的事情..上面列表中的第二个链接使用与您提供的相同的片段。

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.

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.

红ご颜醉 2024-12-28 08:03:24

在第一个实现中,如果从 BaseClass 内部调用 Draw(),输出将为“Draw from Base Class”。但在第二个实现中它将是“从子类中绘制”。这是一个解释:
http://weblogs.sqlteam.com/mladenp/archive/2007 /04/09/60168.aspx

In the first implementation, if you call Draw() from inside BaseClass, the output will be "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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文