Partially Overriding a Virtual Auto-Property in a Child Class

蹲街弑〆低调 提交于 2019-12-03 11:01:41

问题


Time for a theoretical question I just ran across.

The following code is valid and compiles:

public class Parent
{
    public virtual object TestProperty { get; set; }
}

public class Child : Parent
{
    private string _testValue = "Hello World!";

    public override object TestProperty
    {
        get { return _testValue; }
    }
}

public class Consumer
{
    Parent p = new Child();

    public Consumer(){ p.TestProperty = 3; }
}

My question is:

Why does C# allow me to partially override the TestProperty auto property in a child when it leads to partially unpredictable behavior? Is there a practical application?

I'm allowed to set the value of TestProperty using the parent's setter (I checked the IL being generated and the setter is still setting the backing object in the parent class) even though value is not accessible to the public.


回答1:


This behavior is consistent with non-auto-implemented properties in C#. It's always been possible to override only a get or set method for a virtual property. Hence making it impossible to do with an auto-implemented property would create an unnecessary inconsistency.

For example, the following is legal

class A
{
    public virtual int P1
    {
        get { return 42; }
        set { }
    }
}

class B : A
{
    public override int P1
    {
        get { return 18; }
    }
}



回答2:


Doesn't it make sense for a setter, though? If you partially override only the setter, that could be useful so that you can respond to that event, in addition to calling base.TestProperty = value, without having to bother with a boilerplate override of the getter as well.



来源:https://stackoverflow.com/questions/3884025/partially-overriding-a-virtual-auto-property-in-a-child-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!