在子类部分覆盖虚拟自动物业 [英] Partially Overriding a Virtual Auto-Property in a Child Class

查看:118
本文介绍了在子类部分覆盖虚拟自动物业的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

时间一个理论问题,我刚刚跑过

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:

为什么C#让我部分覆盖 TestProperty 自动属性在孩子的时候它会导致部分不可预知的行为?有没有实际应用?

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?

我允许使用父母的制定者(我检查正在生成IL和二传手仍设置在后备对象来设置TestProperty的价值父类),即使价值不向公众开放。

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.

推荐答案

此行为是在非自动实现属性一致C#。这一直可以覆盖只有get或set方法的虚拟财产。因此使得不可能用一个自动实现的属性会造成不必要的不​​一致性做

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.

例如,以下是法律

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

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

这篇关于在子类部分覆盖虚拟自动物业的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆