When you implement two interfaces with the same method, how do you know which one is called?

后端 未结 8 1370
再見小時候
再見小時候 2021-01-13 05:18

If you have TheMethod() in interfaces I1 and I2, and the following class

class TheClass : I1, I2
{
    void TheMethod()
}

If s

8条回答
  •  花落未央
    2021-01-13 05:51

    If you instantiate the class, then you are not using any of the interfaces. If you cast the reference to either interface, then you are using that interface. Example:

    TheClass c = new TheClass();
    c.TheMethod(); // using the class
    
    I1 i = new TheClass();
    i.TheMethod(); // using the I1 interface
    

    As your class is declared, both interfaces will use the same method. You can also specify methods for the class and the separate interfaces:

    class TheClass : I1, I2
    {
      void TheMethod() {} // used by the class
      void I1.TheMethod() {} // used by the I1 interface
      void I2.TheMethod() {} // used by the I2 interface
    }
    

    If you specify only methods for the interfaces, you can't reach the method unless you cast the reference to an interface first:

    class TheClass : I1, I2
    {
      void I1.TheMethod() {} // used by the I1 interface
      void I2.TheMethod() {} // used by the I2 interface
    }
    

    If you specify separate methods for only some interfaces, the other interfaces will use the same implementation as the class:

    class TheClass : I1, I2
    {
      void TheMethod() {} // used by the class and the I1 interface
      void I2.TheMethod() {} // used by the I2 interface
    }
    

提交回复
热议问题