c# - C# 中的虚函数

标签 c# inheritance virtual-functions

public class Base1
{
    public virtual void f()
    {
        Console.WriteLine("Base1.f()");
    }
}

public class Derived1 : Base1
{
    // Hides Base1.f() because 'override' was not specified
    public new virtual void f()
    {
        Console.WriteLine("Derived1.f()");
    }
}

public class Derived2 : Derived1
{
    // Overrides Derived1.f()
    public override void f()
    {
        Console.WriteLine("Derived2.f()");

        // Call base method
        base.f();
    }
}

class Program
{
    static void Main(string[] args)
        Base1 ob1 = new Derived1();
        ob1.f();

        Base1 ob2 = new Derived2();
        ob2.f();

        Derived1 ob3 = new Derived2();
        ob3.f();

        Derived2 ob4 = new Derived2();
        ob4.f();
    }
}


// Calls Derived2.f() because Derived2 overrides Derived1().f()
        Derived1 ob3 = new Derived2();
        ob3.f();

它期待着

Base1 ob2 = new Derived2();
ob2.f();
  1. 将调用 derived2 函数,但调用基类函数 叫 ,这是什么原因。
  2. .net 是否使用 vtables

最佳答案

编译期间静态分析使用的方法槽取决于变量(或表达式)的类型,而不是实际对象。变量 ob2 的类型为 Base1,因此使用了 Base1 方法槽。然后然后根据键入的内容(基本上是该插槽上的 vtable)选择正确的覆盖。所以使用了base函数。

要使用 derived2 函数,变量(或表达式)的类型必须为 Derived1 或子类。

关于c# - C# 中的虚函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5831205/

相关文章:

c++ - 从外部定义的类继承时无效使用不完整类型类错误

c# - 具有多级继承的 base.Method() 未被调用?

c# - 如何通过代码创建新的 Microsoft Azure HybridConnection?

c# - 从基类实例自动创建子类实例

java - 为什么这种类型的继承有效?

c++ - 安全地覆盖 C++ 虚函数

c++ - 使用模板在 C++ 中实现访问者模式

c++ - 本地抽象类的纯虚拟析构函数

c# - 当其他动画正在播放时,如何防止我的动画启动?

c# - 如何使用 dapper 获取第一个子值(通常查询 count(*) 作为唯一结果)