我正在浏览 LitJSON 库。在代码中有很多段,比如
public class JsonData : IJsonWrapper, IEquatable<JsonData>
#region ICollection Properties
int ICollection.Count {
get {
return Count;
}
}
#end region
对于一个方法,我知道覆盖/重载是如何工作的,但在上面的示例中,代码如下:int ICollection.Count
我不熟悉方法签名的格式。编码器是否试图明确声明其 ICollection.Count 接口(interface)?
你能解释一下这是什么“叫”吗(它仍然是最重要的吗?)。
最佳答案
它叫做 explicit interface implementation .主要用于消除不同接口(interface)中存在的同名成员的歧义,这些接口(interface)也需要不同的实现。
考虑一下
interface ISomething1
{
void DoSomething();
}
interface ISomething2
{
void DoSomething();
}
class MyClass : ISomething1, ISomething2
{
void ISomething1.DoSomething()
{
//Do something
}
void ISomething2.DoSomething()
{
//Do something else
}
}
如果没有显式接口(interface)实现,您将无法为我们实现的两个接口(interface)提供不同的 DoSomething
实现。
如果你想实现一些接口(interface)并且你想对客户端隐藏它(在某种程度上)你可以使用显式实现。 Array
类显式实现了 IList
接口(interface),这就是它隐藏 IList.Add
、IList.Remove
等的方式。不过你如果将其转换为 IList
类型,则可以调用它。但是在这种情况下你最终会得到一个异常。
通过显式实现实现的成员在类实例中是不可见的(即使在类内部)。您需要通过接口(interface)实例访问它。
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
关于c# - 编辑接口(interface)时叫什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25585188/