我们都知道虚方法实现多态,抽象方法实现多态等,我们今天来看看如何使用接口实现多态
1.首先我们先要来了解了解什么是接口,它存在的意识
01.接口就是为了约束方法的格式(参数和返回值类型)而存在的
02.接口可以实现多继承,弥补单继承的缺陷。
03.接口可以看成是一个特殊的抽象类,通过反编译看源码可知
04.接口中方法不用访问修饰符,因为CLR会自动添加,并且不能有方法体
05.如果一个类实现了某个接口,就得实现该接口中所有的方法
06.接口要谨慎使用,防止出现接口污染!
07.接口仅仅代表一种能力,实现该接口的类和接口没有继承关系
08.接口是用来实现的,类是用来继承的。
09.其实很多时候,看似可以不用接口,因为接口就是一个方法的约定,
表明你这个类必须要有某些方法,但是不写接口也可以有这些方法,用了接口,
就可以使用接口变量,统一调用,实现多态
10.接口中只能定义方法,不能定义变量。
下面我们举个用接口实现多态的例子:
01.新建一个飞的接口
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
using
System.Threading.Tasks;
namespace
接口
{
//
飞的接口
public
interface
IFly
{
//
接口中方法不用访问修饰符,因为CLR会自动添加,并且不能有方法体
void
Say();
}
}
02.创建一个吃的接口
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
using
System.Threading.Tasks;
namespace
接口
{
//
吃的接口
public
interface
IEat
{
//
接口中方法不用访问修饰符,因为CLR会自动添加,并且不能有方法体
void
eat();
}
}
03.创建一个鸟类来实现飞的接口和吃的接口
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
using
System.Threading.Tasks;
namespace
接口
{
//
鸟实现飞的接口和吃的接口
public
class Grid:IFly,IEat //注意 接口:接口叫继承 ,类:接口叫实现 {
//如果一个类实现了某个接口,就得实现该接口中所有的方法publicvoid Say()
{
Console.WriteLine("鸟在飞");
}
publicvoid eat()
{
Console.WriteLine("鸟在吃");
}
}
}
04.创建一个飞机类实现飞的接口
using
System;
using
System.Collections.Generic;
using
System.Globalization;
using
System.Linq;
using
System.Text;
using
System.Threading.Tasks;
namespace
接口
{
//
飞机实现飞的接口
public
class
Plan:IFly
{
public
void
Say()
{
Console.WriteLine(
"
飞机在飞
"
);
}
}
}
05.在Main方法实现调用
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
using
System.Threading.Tasks;
namespace
接口
{
class
Program
{
static
void Main(string[] args)
{
//定义飞接口数组实例化对象
IFly[] iFlies =
{
new Grid(),
new Plan()
};
//循环数组调用方法实现多态foreach (IFly iFly in iFlies)
{
iFly.Say();
}
//鸟吃实例化对象
IEat iEats = new Grid();
//调用方法实现多态 iEats.eat();
Console.ReadLine();
}
}
}
这样就可实现多态了,运行结果如下:
注:如果有一个类要实现两个接口,不巧的是这两个接口(如:IFly,IPlay)中右两个同命名的方法(Eat)
我们都知道
如果一个类实现了某个接口,就得实现该接口中所有的方法
这怎么办呐?自有解决的方法的:
我们就可以使用接口名.方法来实现
//
实现了IFly和IPlay两个接口,但两个接口中都有Eat方法
public
class
Dog:IFly,IPlay
{
//
如果一个类实现了某个接口,就得实现该接口中所有的方法
//
这样我们就可以使用接口名.方法来实现
void
IFly.Eat()
{
}
void
IPlay.Eat()
{
}
}
原文:http://www.cnblogs.com/zhangzongle/p/5385068.html
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!