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

后端 未结 8 1369
再見小時候
再見小時候 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:58

    If both methods are public then the same method will be called regardless of which interface it was called upon. If you need more granularity, you need to use explicit interface implementations:

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

    Usage might look like:

    TheClass theClass = new TheClass();
    I1 i1 = theClass;
    I2 i2 = theClass;
    
    i1.TheMethod();  // (calls the first one)
    i2.TheMethod();  // (calls the other one)
    

    One thing to keep in mind is that if you make both implementations explicit, you will no longer be able to call TheMethod on variables declared as TheClass:

    theClass.TheMethod();   // This would fail since the method can only be called on the interface
    

    Of course, if you like, you can make only one of the implementations explicit, and keep the other one public in which case calls against TheClass would call the public version.

    0 讨论(0)
  • 2021-01-13 05:59

    That is irrelevant. Casting to any of the interfaces will result in the method being called, but since an interface cannot contain code you cannot inherit behavior from it.

    0 讨论(0)
提交回复
热议问题