在构造函数中访问已实现的抽象属性会导致CA2214:不要在构造函数中调用可覆盖的方法 [英] Accessing an implemented abstract property in the constructor causes CA2214: Do not call overridable methods in constructors
问题描述
public abstract class MyBase
{
public abstract bool MyProperty
{
get;
protected set;
}
}
public class MyClass : MyBase
{
public MyClass()
{
this.MyProperty = true;
}
public override bool MyProperty
{
get;
protected set;
}
}
构造函数MyClass()导致CA2214:
The constructor MyClass() causes CA2214:
不要在构造函数中调用可覆盖的方法。
这通常只显示一个人调用与构造函数在同一个类中定义的虚方法。例如在 MyBase
的构造函数中访问 MyProperty
。在这里,我在派生类的构造函数中调用继承的抽象属性的非虚拟重写实现。
This normally only shows if one calls a virtual method defined in the same class as the constructor. e.g. Accessing MyProperty
inside MyBase
's constructor. Here I am calling a non-virtual overridden implementation of an inherited abstract property inside the derived class' constructor.
推荐答案
不,它仍然是虚拟的,因为覆盖
不会隐式封锁该成员。 (试一试:从 MyClass
派生另一个类,你可以再次覆盖 MyProperty
。)
No, it's still virtual, as override
doesn't seal the member implicitly. (Try it: derive another class from MyClass
, and you can override MyProperty
again.)
你可以明确地密封它:
public override sealed bool MyProperty
{
get;
protected set;
}
此时我希望警告消失。
这篇关于在构造函数中访问已实现的抽象属性会导致CA2214:不要在构造函数中调用可覆盖的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!