在 C# 中,从构造函数调用虚拟方法安全吗?

发布于 2024-11-17 02:29:46 字数 307 浏览 1 评论 0原文

可能的重复:
构造函数中的虚拟成员调用

在C#中,调用虚拟方法是否安全来自构造函数?语言规范怎么说?请同时引用规格。通过安全,我的意思是它会调用派生类的实现吗?

我心中存在这个疑问,因为在 C++ 中,从构造函数调用虚函数是安全的。

Possible Duplicate:
Virtual member call in a constructor

In C#, is it safe to call virtual method from constructor? What does the language specification say? Please quote from the spec as well. By safe, I mean would it call the implementation of the derived class?

This doubt exists in my mind, because in C++, it is not safe to call virtual function from constructor.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

纵性 2024-11-24 02:29:46

你可以这样做,但你不应该这样做。我认为 C# 甚至会给你一个警告。

当该函数被派生类重写时,它变得非常危险,因为您现在在调用派生类的构造函数之前调用该函数。

You can do it, but you shouldn't. I think C# even gives you a warning for it.

It becomes very dangerous when the function has been overridden by a derived class, because you're now calling into that function before the derived class's constructor has been called.

半山落雨半山空 2024-11-24 02:29:46

这是不安全的,因为虚函数将在匹配的构造函数有机会建立类不变量之前被调用。

相比之下,它在 C++ 中是安全的——被调用的函数是在匹配的构造函数期间调用的,而不是之前。

It's not safe, since the virtual function would be called before the matching constructor has had a chance to establish the class invariants.

In contrast, it IS safe in C++ -- the function which is called is called during the matching constructor, not before.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文