编辑界面时它叫什么?
我正在浏览LitJSON库。 在代码中有很多段,如
public class JsonData : IJsonWrapper, IEquatable #region ICollection Properties int ICollection.Count { get { return Count; } } #end region
对于我知道覆盖/重载如何工作的方法,但在上面的示例中,代码为:int ICollection.Count
我不熟悉方法签名的格式。 编码器是否试图明确声明其ICollection.Count接口?
你能解释一下这是什么“被称为”(它是否仍在重写?)。
它被称为显式接口实现 。 主要用于消除不同接口中存在同名的成员的歧义,这些接口也需要不同的实现。
考虑一下你
interface ISomething1 { void DoSomething(); } interface ISomething2 { void DoSomething(); } class MyClass : ISomething1, ISomething2 { void ISomething1.DoSomething() { //Do something } void ISomething2.DoSomething() { //Do something else } }
如果没有显式接口实现,您将无法为我们实现的接口提供不同的DoSomething
实现。
如果要实现某个接口,并且希望将其从客户端隐藏(在某种程度上),则可以使用显式实现。 Array
类显式实现了IList
接口,这就是它隐藏IList.Add
, IList.Remove
等的方法。但是如果你将它转换为IList
类型,你可以调用它。 但在这种情况下你最终会得到一个例外。
通过显式实现实现的成员不能通过类实例(甚至在类中)可见。 您需要通过接口实例访问它。
MyClass c = new MyClass(); c.DoSomething();//This won't compile ISomething1 s1 = c; s1.DoSomething();//Calls ISomething1's version of DoSomething ISomething2 s2 = c; s2.DoSomething();//Calls ISomething2's version of DoSomething
这就是所谓的Explicit Interface Implementation
。 它仅用于在指定接口的实例上公开属性。
如果声明的变量恰好是ICollection类型,则上面提供的示例只会公开Count属性
MSDN
例
这是一个很好的用例,想想一个二十一点游戏,玩家和经销商都将获得两张牌。
经销商只会显示他手中的一张牌,而你将能够看到你的两张牌,所以我们的牌需要一种不同的行为,这取决于客户指定的界面。
public interface IHand { List CurrentHand { get; } } public interface IDealerHand : IHand { } public interface IPlayerHand : IHand { } public class Hand : IDealerHand, IPlayerHand{ private List cardsHeld; // The implementation here will ensure that only a single card for the dealer is shown. List IDealerHand.CurrentHand { get { return cardsHeld.Take(1); } } // The implementation here will ensure that all cards are exposed. List IPlayerHand.CurrentHand { get { return cardsHeld; } } }