在 C# 中,从构造函数调用虚拟方法安全吗?
可能的重复:
构造函数中的虚拟成员调用
在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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你可以这样做,但你不应该这样做。我认为 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.
这是不安全的,因为虚函数将在匹配的构造函数有机会建立类不变量之前被调用。
相比之下,它在 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.