在C#中的继承接口中分离Get / Set属性 [英] Separate Get/Set property in inherited interfaces in C#
问题描述
我有两个接口和一个实现: IState
, IEditableState
和 State
,其中我有一个名为 Value
的整数属性。
I have two interfaces and one implementation: IState
, IEditableState
andState
, in which I have a single integer property called Value
.
我想要使用 IState
到获取此属性, IEditableState
到设置它。
I want to be usingIState
to get this property andIEditableState
to set it.
我的代码看起来如此:
interface IState { int Value { get; } }
interface IEditableState:IState { int Value { set; } }
class State:IEditableState {
int Value { get; set; }
}
显然,我收到 IEditableState的警告。值
隐含地隐藏 IState.Value
,为了清楚起见,我应该添加关键字new。直觉上,这是相同的属性,所以我不明白为什么它应该是新的。
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?
推荐答案
在接口中,无法定义虚拟/覆盖,因此您使用 new
继承接口的实现 - 在类中,这也意味着 Value {get;组; }
和 IState.Value {get; }
并排,即使后者总是引用前者。
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.
或者,这确实出现在.NET框架中本身,并通过为 Readonly
变体提供单独的接口来规避,例如 IList< T>
和 IReadOnlyList< T>
而不是继承的接口;这允许实现具有单个属性,以满足两者中具有相同名称的项。
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.
这篇关于在C#中的继承接口中分离Get / Set属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!