当您使用相同的方法实现两个接口时,您如何知道调用哪个接口?

use*_*055 4 c# interface

如果你有TheMethod()接口I1和I2,以及下面的类

class TheClass : I1, I2
{
    void TheMethod()
}
Run Code Online (Sandbox Code Playgroud)

如果有什么实例化TheClass,它如何知道它正在使用哪个接口?

mus*_*aul 7

如果这就是客户端代码使用该类的方式,那并不重要.如果它需要做一些特定于接口的东西,它应该声明它需要的接口,并将类分配给它,例如

I1 i = new TheClass()
i.TheMethod();
Run Code Online (Sandbox Code Playgroud)

当然,使用您当前的实现TheClass,无论是声明iI1,还是I2,因为您只有一个实现.

如果你想为每个接口单独实现,那么你需要创建显式实现......

    void I1.TheMethod()
    {
        Console.WriteLine("I1");
    }

    void I2.TheMethod()
    {
        Console.WriteLine("I2");
    }
Run Code Online (Sandbox Code Playgroud)

但请记住,显式实现不能公开.您可以只显式实现一个,并将另一个保留为可以公开的默认值.

    void I1.TheMethod()
    {
        Console.WriteLine("I1");
    }

    public void TheMethod()
    {
        Console.WriteLine("Default");
    }
Run Code Online (Sandbox Code Playgroud)

看看msdn文章了解更多细节.


Kir*_*oll 5

如果两个方法都是公共的,则无论调用哪个接口,都将调用相同的方法.如果您需要更多粒度,则需要使用显式接口实现:

class TheClass : I1, I2
{
    void I1.TheMethod() {}
    void I2.TheMethod() {}
}
Run Code Online (Sandbox Code Playgroud)

用法可能如下所示:

TheClass theClass = new TheClass();
I1 i1 = theClass;
I2 i2 = theClass;

i1.TheMethod();  // (calls the first one)
i2.TheMethod();  // (calls the other one)
Run Code Online (Sandbox Code Playgroud)

要记住的一件事是,如果你使两个实现都是显式的,你将不再能够调用TheMethod声明为的变量TheClass:

theClass.TheMethod();   // This would fail since the method can only be called on the interface
Run Code Online (Sandbox Code Playgroud)

当然,如果你愿意,你可以只显示其中一个实现,并保持另一个公开,在这种情况下,调用TheClass将调用公共版本.