以下继承有什么区别
这是简单的继承
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在第二个片段中,Draw 被声明为虚拟的,这意味着您可以从
BaseClass
类型的变量调用继承的方法。文档
有趣的事情..上面列表中的第二个链接使用与您提供的相同的片段。
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
.Documentation
Funny thing.. the second link in the list above uses the same snippets as you've provided.
在第一个实现中,如果从
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 insideBaseClass
, 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