构造函数中的虚构成员调用

编程入门 行业动态 更新时间:2024-10-27 03:33:26
本文介绍了构造函数中的虚构成员调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我从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.

更多推荐

构造函数中的虚构成员调用

本文发布于:2023-11-22 07:07:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1616436.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   成员

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!