在构造函数中的虚拟成员调用 [英] Virtual member call in a constructor

查看:200
本文介绍了在构造函数中的虚拟成员调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我碰到ReSharper的有关从我的对象构造一个虚拟成员的呼叫警告。为什么会变成这样的东西不要做?

I'm getting a warning from ReSharper about a call to a virtual member from my objects constructor. Why would this be something not to do?

推荐答案

(假设你在C#写在这里)

(Assuming you're writing in C# here)

在C#编写的一个对象被构造,会发生什么情况是,初始化为了从最派生类的基类中运行,然后从基类最派生类,以构造运行(<一个href=\"http://blogs.msdn.com/ericlippert/archive/2008/02/18/why-do-initializers-run-in-the-opposite-order-as-constructors-part-two.aspx\">see埃里克利珀的博客的详细信息,为什么这是)。

When an object written in C# is constructed, what happens is that the initializers run in order from the most derived class to the base class, and then constructors run in order from the base class to the most derived class (see Eric Lippert's blog for details as to why this is).

此外,在为他们构建.NET对象不改变类型,但开始作为最派生类型,在方法表是为最派生类型。这意味着,虚拟方法调用总是在最派生类型运行。

Also in .NET objects do not change type as they are constructed, but start out as the most derived type, with the method table being for the most derived type. This means that virtual method calls always run on the most derived type.

当你把你留下这两个事实的问题,如果您在构造一个虚拟的方法调用,它是不是在它的继承层次最派生类型,它会在一个类的构造函数被调用尚未运行,因此可能无法在一个适当的状态已调用该方法。

When you combine these two facts you are left with the problem that if you make a virtual method call in a constructor, and it is not the most derived type in its inheritance hierarchy, that it will be called on a class whose constructor has not been run, and therefore may not be in a suitable state to have that method called.

这问题,当然,如果你标记您的类密封,以确保它在继承层次的最派生类型缓解 - 在这种情况下,它是绝对安全的调用虚拟方法

This problem is, of course, mitigated if you mark your class as sealed to ensure that it is the most derived type in the inheritance hierarchy - in which case it is perfectly safe to call the virtual method.

这篇关于在构造函数中的虚拟成员调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆