当您使用相同的方法实现两个接口时,您如何知道哪个被称为? [英] When you implement two interfaces with the same method, how do you know which one is called?

查看:72
本文介绍了当您使用相同的方法实现两个接口时,您如何知道哪个被称为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果接口I1和I2中具有TheMethod(),并且具有以下类

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

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

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

If something instantiates TheClass, how does it know which interface it is using?

推荐答案

如果那是客户端代码使用该类的方式,那实际上没有关系.如果需要执行特定于接口的操作,则应声明所需的接口,并将该类分配给该接口,例如

If that's how the client code is using the class, it doesn't really matter. If it needs to do something interface specific, it should declare the interface it needs, and assign the class to that e.g.

I1 i = new TheClass()
i.TheMethod();

当然,使用您当前的实现TheClass,将i声明为I1I2并不重要,因为您只有一个实现.

Of course, using your current implementation TheClass, it doesn't matter if declared i as I1, or I2, as you only have a single implementation.

如果每个接口需要单独的实现,则需要创建显式实现...

If you want a separate implementation per interface, then you need to create explicit implementations ...

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

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

但是请记住,显式实现不能公开.您可以只显式地实现一个,而将另一个保留为默认值,可以将其设置为公共.

But keep in mind, explicit implementations cannot be public. You can implement just one explicitly, and leave the other as the default which can be public.

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

    public void TheMethod()
    {
        Console.WriteLine("Default");
    }

有关更多详细信息,请参见 msdn文章.

Have a look the msdn article for more details.

这篇关于当您使用相同的方法实现两个接口时,您如何知道哪个被称为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆