What is it called when you edit an interface?

后端 未结 2 509
梦谈多话
梦谈多话 2020-12-21 00:17

I am going through a LitJSON library. In the code there are lots of segments like

 public class JsonData : IJsonWrapper, IEquatable

 #region         


        
2条回答
  •  清酒与你
    2020-12-21 00:59

    It is called explicit interface implementation. Mainly used to disambiguate members with same name present in different interfaces which also needs different implementation.

    Consider you have

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

    Without Explicit interface implementation you will not be able to provide different implementation of DoSomething for both the interfaces we implement.

    If you want to implement some interface and you want to hide it from the client(upto some extent) you can use explicit implementation. Array class implements IList interface explicitly and that's how it hides IList.Add, IList.Remove etc. Nevertheless you can call it if you cast it to IList type. But you'll end up getting an Exception in this case.

    Members implemented via explicit implementations are not visible via class instance(Even inside the class). You need to access it via interface instance.

    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
    

提交回复
热议问题