[英]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.