Two interfaces have same method

心不动则不痛 提交于 2021-02-16 20:26:13

问题


Interface A
{
    int Add(int a,int b);
}

Interface B
{
    int Add(int a,int b);
}

Class D : A, B
{
    int Add(int a,int b)
    {
        return a+b;
    }
}

Code works fine and didn't produce any error. Class D is using which interface's method?


回答1:


Neither, since neither interface HAS a method, merely a method signature. Your method in D implements the signature provided by both interfaces, so it works.

Remember, an interface merely specifies the signatures of methods that must exist in an implementation.




回答2:


Since method signatures are the same on both interfaces, and class D implements those methods (with a single function), then it doesn't really matter which interface that function implements, and thus compiler is happy.

However, you can have two different implementations specific for each interface by declaring functions as

class D : A, B
{
    int A.Add(int a, int b)
    {
    }

    int B.Add(int a, int b)
    {
    }
}



回答3:


Class D is using which interface's method?

Neither. Interfaces don't have methods, they only define the method signatures which the implementations should have. You're thinking of it backwards.

  • D doesn't use A's or B's method.
  • A uses D's method on any instance of A which has D as it's implementation.
  • B uses D's method on any instance of B which has D as it's implementation.

D satisfies both interfaces A and B by providing that method.



来源:https://stackoverflow.com/questions/22536233/two-interfaces-have-same-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!