Separate Get/Set property in inherited interfaces in C# [duplicate]

寵の児 提交于 2019-12-24 09:29:37

问题


I have two interfaces and one implementation: IState, IEditableState andState, in which I have a single integer property called Value.

I want to be usingIStateto get this property andIEditableState to set it.

My code looks thusly:

interface IState { int Value { get; } }

interface IEditableState:IState { int Value { set; } }

class State:IEditableState {
    int Value { get; set; }
}

Apparently, I get a warning that IEditableState.Value implicitely hides IState.Value and that I should add the keyword new for clarity. Intuitively, this is the same property so I don't understand why it should be new.

What would be the "clean" way to do this?


回答1:


How about this approach? implement your interfaces with a method instead of a property, and then explicitly implement the interfaces in State and abstract the method calls behind a property Value. Here is a code sample:

interface IState { int GetValue(); }

interface IEditableState : IState { void SetValue(int value); }

class State : IEditableState
{
    public int Value
    {
        get 
        { 
            return (this as IState).GetValue(); 
        }
        set
        {
            (this as IEditableState).SetValue(value);
        }
    }

    private int _value;
    int IState.GetValue()
    {
        return _value;
    }

    void IEditableState.SetValue(int value)
    {
        _value = value;
    }
}



回答2:


In interfaces, there is no way to define virtual/overrides, so you're stuck using a new implementation for inherited interfaces - in classes, this will also mean a Value { get; set; } and IState.Value { get; } side by side, even if the latter is always going to reference the former.

Alternatively, this does come up in the .NET framework itself, and is circumvented by having a separate interface for the Readonly variants, such as with IList<T> and IReadOnlyList<T>, rather than an inherited interface; this allows implementations to have a single property that satisfies those items with the same name in both.




回答3:


"new" keyword is needed because property name in both the base and inherited interfaces is same and you also haven't overridden the property of base interface. When this is the case, you need to specify new keyword. In this case you will hide the property of base interface i.e. you will be able to use property of derived interface only.

Another way to do this is to define two separate properties with different names as given below:


interface IState { int ValueGet { get; } }

interface IEditableState:IState { int ValueSet { set; } }

class State:IEditableState {
    int ValueGet { get;  }
    int ValueSet { set; }
}



来源:https://stackoverflow.com/questions/37657045/separate-get-set-property-in-inherited-interfaces-in-c-sharp

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