c# - 在构造函数或析构函数中调用的虚函数的行为

标签 c# c++ constructor virtual

我已经阅读了一些关于在 c++ 和 c# 之间的构造函数或析构函数中调用的虚函数的不同行为的资料。我测试下面的代码以确认 c# 可以调用 virtual dirived 虚函数,因为它的对象存在于构造函数之前。但是我发现结果与 C++ 中的类似代码相同。谁能告诉我为什么 c# 不能显示“22”而只能显示“12”的原因。

C#代码

public class Base
{
    public Base() { fun(); }
    public virtual void fun() { Console.WriteLine(1); }
}
public class Derived : Base
{
    public Derived() { fun(); }
    public virtual void fun() { Console.WriteLine(2); }
}

C++代码

class Base
{
public:
    Base(){fun();}
    virtual void fun(){cout<<1;}
};
class Derived : Base
{
public:
    Derived(){fun();}
    virtual void fun(){cout<<2;}
};

c++和C#的输出结果都是“12”。

最佳答案

您的 C# 代码中有错误。

要覆盖 C# 函数,您必须指定 override 关键字。 如果您再次编写 virtual,您将隐藏基本函数,但如果没有 new 关键字,您应该会收到警告。

如果两者都声明为虚函数,则您有两个同名函数!

让我们举个例子...

public class Base
{
    public Base() { fun(); }
    public virtual void fun() { Console.Write(1); }
}

public class Derived : Base
{
    public Derived() { fun(); }
    public override void fun() { Console.Write(2); }
}

public class DerivedWithError : Base
{
    public DerivedWithError() { fun(); }
    public new virtual void fun() { Console.Write(3); }
}

...

// This will print "22".
Base normal = new Derived();
Console.WriteLine();

// This will print "13" !!!
Base withError = new DerivedWithError ();
Console.WriteLine();

// Let's call the methods and see what happens!

// This will print "2"
normal.fun();
Console.WriteLine();

// This will print "1" !!!
withError.fun();
Console.WriteLine(); 

Shadowing 的意思是“在不使用多态性的情况下添加一个同名的新方法”。 如果没有 override 关键字,您将禁用多态性。

所以现在一切都应该干净且易于理解。

DerivedWithError.fun() 是一种全新的虚拟方法。它与基类中的函数 fun 同名,但它们没有关系!

从虚表(或虚方法表,如果你喜欢另一个名字)的角度来看,带阴影的基函数和派生函数在虚表中占据两个不同的条目,如果它们具有相同的名称. 如果改用override,就是强制派生类中的func方法覆盖Base.func占用的虚表项,这就是多态。

危险但 .NET 允许,请始终注意语法!

您可以在 C# 的构造函数中调用虚函数,但通常在派生类中,如果在基类构造函数中调用方法,您应该注意在派生类中如何使用字段。 现在,为了干净并避免混淆和风险,您应该避免在构造函数中调用虚方法,但实际上它在几次时都非常有用。

例如所谓的“工厂方法”,它不访问任何变量。

public abstract class MyClass
{
    public IList<string> MyList { get; private set; }

    public MyClass()
    {
         this.MyList = this.CreateMyList();
    }

    protected abstract IList<string> CreateMyList();
}

public class MyDerived : MyClass
{
    protected override IList<string> CreateMyList()
    {
        return new ObservableCollection<string>();
    }
}

这是完全合法的,而且有效!

关于c# - 在构造函数或析构函数中调用的虚函数的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8058772/

相关文章:

python - 遍历构造函数的参数

c# - 与 LINQ 相关的具有 2 个条件的转换左外连接

c++ - 在 C++ 中抓取递归 ntfs 目录的最快方法

c++ - C++错误:没有匹配的构造函数用于初始化

c++ - Qt 判断 QSpinBox 是否被用户更改

c++ - 在 C++ 中解析逗号分隔的数字

.net - 正则表达式的默认初始化选项是什么?

c# - 将 System.Array 的 C# 十进制值转换为字符串

c# - 连接到数据库失败。检查连接字符串是否正确以及 DbContext 构造函数

c# - 通过命令行创建 7-Zip 存档时创建逻辑文件夹结构