3 回答

TA贡献1776条经验 获得超12个赞
您可以实现明确一个接口和另一个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");

TA贡献1829条经验 获得超6个赞
通过显式实现接口,如下所示:
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();
- 3 回答
- 0 关注
- 747 浏览
添加回答
举报