一小段代码演示C#接口的类级别实现和显式接口成员实现
来源:互联网 发布:大数据技术与应用就业 编辑:程序博客网 时间:2024/05/24 06:00
拿《C#图解教程》书中代码做的试验:
using System;namespace Examples{ interface IIfc1 { void PrintOut( string s ); } interface IIfc2 { void PrintOut( string t ); } class MyClass : IIfc1, IIfc2 { void IIfc1.PrintOut( string s ) // 显式接口成员实现 { Console.WriteLine( "IIfc1: {0}", s ); } void IIfc2.PrintOut( string s ) // 显式接口成员实现 { Console.WriteLine( "IIfc2: {0}", s ); } public void PrintOut(string s) // 类级别实现 { Console.WriteLine("MyClass: {0}", s); } } class Program { static void Main() { MyClass mc = new MyClass(); mc.PrintOut( "Hello" ); IIfc1 ifc1 = (IIfc1) mc; ifc1.PrintOut( "Hello" ); IIfc2 ifc2 = (IIfc2) mc; ifc2.PrintOut( "Hello" ); }// 设置断点 }}/*输出:MyClass: HelloIIfc1: HelloIIfc2: Hello*/
如果 只有 显式接口成员的实现,没有 类级别的实现,那么 不能直接用MyClass的引用访问实现,只能强制转换为接口的引用才能访问实现。例如:
using System;namespace Examples{ interface IIfc1 { void PrintOut( string s ); } interface IIfc2 { void PrintOut( string t ); } class MyClass : IIfc1, IIfc2 { void IIfc1.PrintOut( string s ) { // implementation Console.WriteLine( "IIfc1: {0}", s ); } void IIfc2.PrintOut( string s ) { // implementation Console.WriteLine( "IIfc2: {0}", s ); } public void Method1( string s ) { // this.PrintOut(s); It does not exist! ((IIfc1) this).PrintOut(s); } } class Program { static void Main() { MyClass mc = new MyClass(); IIfc1 ifc1 = (IIfc1) mc; ifc1.PrintOut( "Hello" ); IIfc2 ifc2 = (IIfc2) mc; ifc2.PrintOut( "Hello" ); mc.Method1( "Hello" ); }// 设置断点 }}/*输出:IIfc1: HelloIIfc2: HelloIIfc1: Hello*/
0 0
- 一小段代码演示C#接口的类级别实现和显式接口成员实现
- C#显式接口实现和隐式接口实现
- C#接口-显式接口和隐式接口的实现
- 【转】C#接口-显式接口和隐式接口的实现
- C#继承接口的类和派生接口的实现
- C#接口-接口的实现
- C#隐式实现接口成员与显示实现接口成员
- C#隐式实现接口成员与显示实现接口成员
- C#中接口的显式和隐式实现
- C#中接口的显式和隐式实现
- C#中接口的显式和隐式实现
- 接口成员的显示实现
- C#接口的实现
- C#接口的实现
- C#接口的实现
- C#中,接口的隐式实现和显示实现
- C#接口的显示实现和隐式实现
- C# (不实现接口成员)
- MYSQL数据库引擎分析
- 字符串匹配算法总结
- 黑马程序员——结构体
- Visual Studio 2013开发 mini-filter driver step by step 应用层与内核通讯(8)
- mysql之union联合查询、子查询、连接查询
- 一小段代码演示C#接口的类级别实现和显式接口成员实现
- 程序语言基础知识总结
- oracle如何保证事务的ACID原则--oracle核心技术读书笔记二
- 重载重写与重定义
- C++对象在内存中的布局(读汇编代码)
- ARM接口技术——基础
- Android上的otto的使用
- hdu2050折线分割平面
- HTML元素显示与隐藏