将 Get/Set 属性 覆盖为 Get-Only 仍然可以让您设置它

Overriding a Get/Set Property to Be Get-Only Still Lets You Set It

考虑这个简短的例子:

class Program
{
    private abstract class PropertyExample
    {
        public virtual bool Property { get; set; }
    }

    private class GetOnlyProperty : PropertyExample
    {
        private bool property = false;
        public override bool Property => property;
    }

    static void Main(string[] args)
    {
        GetOnlyProperty example = new GetOnlyProperty();
        example.Property = true;
    }
}

即使我将 GetOnlyProperty class 中的 Property 覆盖为仅获取,我仍然可以在 Main() 中设置它。为什么这可能?

该语言不允许您完成您在此处尝试完成的任务。 Liskov 替换原则要求派生的 class 可以在任何需要基数 class 的地方替换。为了使 属性 成立,基 class 接口的每个可访问成员都必须存在并且在派生的 class.

中可以访问

通过查看生成的 CIL 代码,结果表明您通过在派生的 class:

中将其设置为只读来覆盖 getter 方法
public override bool Property => property;

但仍然继承了setter,所以当你设置属性时,你仍然可以访问基础class.[=11]的setter方法=]