c# - 编辑接口(interface)时叫什么?

标签 c# json interface overriding ienumerable

我正在浏览 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.AddIList.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/

相关文章:

javascript - JSTree 的 data.rslt.obj.text() 返回一个文本数组,而不是来自所需节点的文本

jquery - MagicSuggest - 设置带有预选项目的魔术建议列表

c# - 当应用程序进行全局化和本地化时,我必须做和不应该做的事情是什么?

c# - LINQ - 通过 WHERE 子句查询大约 6000 条唯一记录

java - 列表到 Json 数组 InvocationTargetException

java - 接口(interface),如果不是所有实现都使用所有方法怎么办?

android - 波处理和 Raspberry Pi

go - Go语言上的接口(interface)函数调用

c# - 无法使用直线在 Webchat 中发送附件,相同的代码在模拟器中运行良好

c# - 有没有办法将元组重建为兼容类?