c# - 多态与继承

标签 c# inheritance polymorphism

我有这些类(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/

相关文章:

java - 静态方法继承和多态

c# - ASP.Net 导航栏和 gridview 错误

c# - ASP.NET MVC Htmlhelper htmlAttributes 不起作用

c# - 如何使用虚方法显式实现接口(interface)?

c# - 如果一个类正在使用一个接口(interface),它必须

c# - 从父类调用派生方法 C#

c# - 方法完成后在方法中创建的控件会发生什么情况?

c# - GridView 中的 Row_DataBound 或 Row_Created 事件

c++ - 比多态性更简洁的代码替代方案

c++ - 调用基类转换为派生类的函数