Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
432 views
in Technique[技术] by (71.8m points)

c# - 构造函数中的虚拟成员调用(Virtual member call in a constructor)

I'm getting a warning from ReSharper about a call to a virtual member from my objects constructor.

(我从ReSharper得到警告,关于从对象构造函数调用虚拟成员的信息。)

Why would this be something not to do?

(为什么这不是要做的事情?)

  ask by JasonS translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 ).

(构造用C#编写的对象时,发生的事情是初始化程序从最派生类到基类按顺序运行,然后构造函数从基类到最派生类按顺序运行( 有关详细信息,请参见Eric Lippert的博客)关于这是为什么 )。)

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.

(同样,在.NET中,对象在构造时不会更改类型,而是从最派生的类型开始,方法表用于最派生的类型。)

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.

(如果将您的类标记为密封以确保其是继承层次结构中最派生的类型,则可以缓解此问题-在这种情况下,调用虚方法是绝对安全的。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...