小编典典

当您编辑界面时,这叫什么?

json

我正在通过一个LitJSON库。在代码中有很多段,例如

 public class JsonData : IJsonWrapper, IEquatable<JsonData>

 #region ICollection Properties
            int ICollection.Count {
                get {
                    return Count;
                }
            }
    #end region

对于一种方法,我知道重写/重载的工作方式,但是在上面的示例中,代码显示为:int ICollection.Count

我对方法签名的格式不熟悉。编码人员是否正在尝试明确声明其ICollection.Count接口?

您能否解释一下这就是所谓的(仍在覆盖?)。


阅读 270

收藏
2020-07-27

共1个答案

小编典典

这称为显式接口实现。主要用于消除在不同接口中存在的具有相同名称的成员的歧义,这也需要不同的实现。

认为你有

interface ISomething1
{
    void DoSomething();
}

interface ISomething2
{
    void DoSomething();
}

class MyClass : ISomething1, ISomething2
{
    void ISomething1.DoSomething()
    {
        //Do something
    }

    void ISomething2.DoSomething()
    {
        //Do something else
    }
}

没有Explicit接口实现,您将无法DoSomething为我们实现的两个接口提供不同的实现。

如果要实现某个接口,并且想在客户端中隐藏它(在某种程度上),则可以使用显式实现。ArrayIList显式实现接口,这就是隐藏的方式IList.AddIList.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
2020-07-27