参考书目:C#6.0学习笔记——从第一行C#代码到第一个项目设计(作者周家安)P87
目的:学习C#中的接口概念和实现方式
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;
namespace Example3_10
{
class Program
{
static void Main(string[] args)
{
Test t = new Test(); //定义类的实例
((ITest1)t).Run(); //调用ITest1.Run方法
((ITest2)t).Run(); //调用ITest2.Run方法
ReadKey();
}
}
//接口1
public interface ITest1
{
void Run();
}
//接口2
public interface ITest2
{
void Run();
}
//定义一个类,显式实现这两个接口
public class Test : ITest1, ITest2
{
void ITest1.Run()
{
//为什么Visual Studio要添加throw new NotImplementedException();而不是直接留空呢。
/*
原因我想有2:
一个是对于那些有返回值的方法,如果什么都不写,
会无法通过编译,VS不希望这样;
另一个原因是,NotImplementedException();
可以表示真的没有实现这个方法。对于可以预见的调用者,
它们可能真的只需要使用接口中的一些方法。因此完全没有必要
实现所有的方法。NotImplementedException(); 保证了不实现某些方法,
代码仍然合法,同时对调用的违例给出异常提示。
*/
//处理方法:直接删除如下自动生成的语句
//throw new NotImplementedException();
WriteLine("调用了ITest1.Run()的方法");
}
void ITest2.Run()
{
//throw new NotImplementedException();
WriteLine("调用了ITest2.Run()的方法");
}
}
}
运行结果如下: