从具有相同方法名称的多个接口继承 [英] Inheritance from multiple interfaces with the same method name

查看:19
本文介绍了从具有相同方法名称的多个接口继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我们有一个继承自多个接口的类,并且这些接口有同名的方法,我们如何在我的类中实现这些方法?如何指定实现哪个接口的哪个方法?

If we have a class that inherits from multiple interfaces, and the interfaces have methods with the same name, how can we implement these methods in my class? How can we specify which method of which interface is implemented?

推荐答案

通过显式实现接口,像这样:

By implementing the interface explicitly, like this:

public interface ITest {
    void Test();
}
public interface ITest2 {
    void Test();
}
public class Dual : ITest, ITest2
{
    void ITest.Test() {
        Console.WriteLine("ITest.Test");
    }
    void ITest2.Test() {
        Console.WriteLine("ITest2.Test");
    }
}

当使用显式接口实现时,函数在类上不是公共的.因此,为了访问这些函数,您必须首先将对象强制转换为接口类型,或者将其分配给声明为接口类型的变量.

When using explicit interface implementations, the functions are not public on the class. Therefore in order to access these functions, you have to first cast the object to the interface type, or assign it to a variable declared of the interface type.

var dual = new Dual();
// Call the ITest.Test() function by first assigning to an explicitly typed variable
ITest test = dual;
test.Test();
// Call the ITest2.Test() function by using a type cast.
((ITest2)dual).Test();

这篇关于从具有相同方法名称的多个接口继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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