设为首页 加入收藏

TOP

C# explicit interface implementation(显式接口实现)
2019-09-17 18:12:24 】 浏览:18
Tags:explicit interface implementation 接口 实现

C# explicit interface implementation

某个类要实现两个包含相同方法名的接口, 应该如何实现这两个方法?

 1 namespace ExplicitInterfaceImplementation
 2 {
 3     class Program : IPrintOne,IPrintTwo, IPrintThree
 4     {
 5         static void Main(string[] args)
 6         {
 7             Program p = new Program();
 8             p.Print();
 9             (p as IPrintTwo).Print();
10             ((IPrintThree)p).Print();
11         }
12 
13 
14 
15         public void Print()
16         {
17             Console.WriteLine("Print One Interface");
18         }
19         // explicitly implement IPrintTwo
20         void IPrintTwo.Print()
21         {
22             Console.WriteLine("Print Two Interface");
23         }
24         // explicitly implement IPrintThree
25         string IPrintThree.Print()
26         {
27             Console.WriteLine("Print two Interface");
28             return "asd";
29         }
30     }
31 
32     interface IPrintOne
33     {
34         void Print();
35     }
36 
37     interface IPrintTwo
38     {
39         void Print();
40     }
41 
42     interface IPrintThree
43     {
44         string Print();
45     }
46 }

 

以上Demo中共有3个拥有相同方法名的interface,Program类继承了这三个接口,使用explicit interface implementation实现IPrintTwo和IPrintThree接口的方法

显示实现的接口方法前不能加access modifier,且调用该方法时需将Program类转换位接口才能调用, 不能直接通过类引用调用。

When a class explicitly implements an interface member, the interface member can no longer be accessed thru class reference variable, but only thru the interface reference variable.

以上Demo的运行结果:

Print One Interface  
Print Two Interface  
Print Three Interface  

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇azure 上传blob到ams(CreateFromB.. 下一篇asp.net core系列 64 结合eShopOn..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目