简体   繁体   English

具有私有设置器的继承的自动实现属性

[英]Inherited auto-implemented property with private setter

I have a base class and a derived class. 我有一个基类和一个派生类。 Each has the same property which has a private setter so the value can be set by some logic inside the class. 每个属性都具有相同的属性,该属性具有一个private setter,因此可以通过类中的某些逻辑来设置值。

class First
{
    internal virtual int Value { get; private set; }

    void SetValue(int toValue)
    {
        Value = toValue;
    }
}

class Second : First
{
    internal override int Value { get; private set; }

    void SetValue(int toValue)
    {
        Value = toValue;
    }
}

This is resulting in a compiler error: 这导致编译器错误:

The property or indexer ... cannot be used in this context because the set accessor is inaccessible. 该属性或索引器...不能在此上下文中使用,因为设置的访问器不可访问。

Why is that the case, and how can I achieve what I'm trying to do? 为什么会这样,我如何实现我想要做的事情? Is this not possible with auto-implemented properties, in other words, do I have to use a backing field instead? 使用自动实现的属性无法做到这一点,换句话说,我是否必须使用后备字段?

Second would be unable to set the value of Value from First due to Value s setter being private . Second是不能set的值ValueFirst ,由于Value小号二传手是private If you need your subclass to be able to set it, it needs to be protected in the base. 如果您需要子类能够进行设置,则需要在基类中对其进行protected

Getters and Setters are basically methods. Getter和Setter基本上是方法。 You can't override methods you can't see. 您无法覆盖看不见的方法。 The virtual in this case only applies to the getter as virtual private is not allowable. 在这种情况下, virtual仅适用于吸气剂,因为不允许使用virtual private

It's not just that you can't see it to use it, you cannot override it at all. 不仅仅是您看不到要使用它,而且根本无法覆盖它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM