为了账号安全,请及时绑定邮箱和手机立即绑定

从具有相同方法名称的多个接口继承

从具有相同方法名称的多个接口继承

C#
qq_笑_17 2019-12-13 11:10:10
如果我们有一个从多个接口继承的类,并且这些接口具有名称相同的方法,那么如何在我的类中实现这些方法?我们如何指定实现哪个接口的方法?
查看完整描述

3 回答

?
米脂

TA贡献1836条经验 获得超3个赞

您可以实现明确一个接口和另一个implecitely。


public interface ITest {

    void Test();

}

public interface ITest2 {

    void Test();

}

public class Dual : ITest, ITest2

{

    public void Test() {

        Console.WriteLine("ITest.Test");

    }

    void ITest2.Test() {

        Console.WriteLine("ITest2.Test");

    }

}

ITest.Test将是默认实现。


Dual dual = new Dual();

dual.Test();

((ITest2)dual).Test();

输出:


Console.WriteLine("ITest.Test");

Console.WriteLine("ITest2.Test");



查看完整回答
反对 回复 2019-12-14
?
千万里不及你

TA贡献1784条经验 获得超9个赞

通过显式实现接口,如下所示:


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");

    }

}

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


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();



查看完整回答
反对 回复 2019-12-14
  • 3 回答
  • 0 关注
  • 328 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信