Accessing an implemented abstract property in the

2019-04-22 05:03发布

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;
    }
}

The constructor MyClass() causes CA2214:

Do not call overridable methods in constructors.

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.

1条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-04-22 05:19

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

You could seal it explicitly though:

public override sealed bool MyProperty
{
    get;
    protected set;
}

At that point I'd expect the warning to go away.

查看更多
登录 后发表回答