显示接口实现

如果一个类继承了多个接口,而接口又有同名的方法或属性,这时就要考虑用显示接口实现,避免错误!

例:

1 class Program
2 {
3 static void Main(string[] args)
4 {
5 MyClass a = new MyClass();
6 a.show();
7 }
8 }
9
10 class MyClass :Interface1,Interface2
11 {
12 public void show()
13 {
14 Console.Write("实现接口");
15 }
16 }
17
18 interface Interface1
19 {
20 void show();
21 }
22
23 interface Interface2
24 {
25 void show();
26 }

此时应该改成:

class Program
{
static void Main(string[] args)
{
MyClass a
= new MyClass();
Interface1 b
= a;
b.show();
}
}

class MyClass :Interface1,Interface2
{

void Interface1.show()
{
Console.Write(
"实现接口1");
}

void Interface2.show()
{
Console.Write(
"实现接口2");
}
}

其实地方不变!

注意:显示接口实现,不能用类的对象去调用方法!

相关文章:

  • 2022-01-05
  • 2021-11-23
  • 2021-11-25
  • 2022-01-17
  • 2022-12-23
  • 2021-11-30
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-01-29
  • 2022-12-23
  • 2022-01-26
  • 2021-10-19
相关资源
相似解决方案