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

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

问题描述

我从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#编写的对象被构​​造时,发生的情况是初始化器按照从最大派生类到基类的顺序运行,然后构造函数按照从基类到最大派生类()。

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天全站免登陆