我有这些类(class):
class A
{
public int Foo()
{
return 5;
}
}
class B : A
{
public int Foo()
{
return 1;
}
}
我这样使用它们:
B b = new B();
int x = b.Foo();
尽管基类或派生类中的 Foo() 不是虚拟的 - 它没有 override 关键字,但 x 仍然等于 1。那么,virtual 和 override 关键字的用途是什么?
最佳答案
多态性允许将类型 B 视为类型 A。
A b = new B();
int x = b.Foo(); // x will be 1 if virtual, 5 if not.
关于c# - 多态与继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7866929/