[英]Explicit interface implementaion with second implementation
我正在追踪一个错误,我在Avalon Dock 2.0源代码中找到了这个:
public abstract class LayoutContent : LayoutElement, /* ... */, ILayoutPreviousContainer
{
// ...
[XmlIgnore]
string ILayoutPreviousContainer.PreviousContainerId
{
get;
set;
}
protected string PreviousContainerId
{
get { return ((ILayoutPreviousContainer)this).PreviousContainerId; }
set { ((ILayoutPreviousContainer)this).PreviousContainerId = value; }
}
}
ILayoutPreviousContainer
有一个成员string PreviousContainerId { get; set; }
string PreviousContainerId { get; set; }
string PreviousContainerId { get; set; }
。
这种模式有什么作用? 我知道除非您首先将LayoutContent
ILayoutPreviousContainer
转换为ILayoutPreviousContainer
否则无法从继承子树外部获取/设置PreviousContainerId
。 但我不明白为什么你会想要这个。
在研究这种模式后,我发现这个SO帖子让我更加困惑。 通过这种方式实现它,它看起来类似于只有一个virtual
属性,它将以一种复杂的方式实现:
public class SpecificLayoutContent : LayoutContent, ILayoutPreviousContainer
{
// override LayoutContent.PreviousContainerId since it casts 'this' to an ILayoutPreviousContainer
// which will then call this property
string ILayoutPreviousContainer.PreviousContainerId{ /* ... */ }
}
我错过了什么吗?
protected
属性无法隐式或显式地实现接口属性。 因此,如果您希望从此类和派生类轻松直接访问,则需要一个protected
属性和另一个显式实现该接口的“隐藏”属性。
看一下你的例子,可以考虑切换两个属性的角色,这样protected
的属性就是一个自动属性,而实现一个属性的接口是指自动属性(而不是相反)。
您看到了什么选择? 如果将其public
(因此隐式实施),可以坚持单一财产,但在这种情况下,财产将暴露更多,这显然是不希望的。
ILayoutPreviousContainer
似乎是一个internal
接口。 因此,就SpecificLayoutControl
外部用户而言,接口不存在,并且只在类PreviousContainerId
定义了PreviousContainerId
属性。
通常的规则适用于是应该protected
还是public
。 我不会对此进行扩展,因为这似乎不是你的问题所在。
该班的作者已决定该财产应受到protected
。 但是,如果它protected
,则无法实现接口的属性,尽管外部用户看不到该接口,但在其他地方内部需要该接口。 所以,他们像这样实现它,其中一个属性仅仅转发给另一个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.