【转】C#笔记之接口(Interface)
原文: 小贱学C#笔记之接口(Interface)
与各个大牛比起来,我还是个刚接触游戏开发不久的新手。但是我总不能一直停留在崇拜他们的阶段,只有不断的去学习,去熟悉,才有可能有一天也被别人崇拜。
今天我来整理一下接口的相关。对于大多刚接触编程的新手来说,应该总有想法觉得,接口是个没什么用的东西(之前我也是)。感觉接口中就是声明了点属性,还有方法名,没什么实际意义。现在我不多做解释,先来使用一下接口,说不定用完突然就觉得还挺好使的呢!
比如我们现在做一个FPS游戏,里面玩家可以选择三种职业的兵种:步兵,坦克兵,治疗兵。他们都有自己的专属技能UseRPG(),DriveTank(),Treat(),而且他们都有通用技能Walk(),Run(),Shoot()。好了,前面的都是前提,现在开始写代码,先写接口IPlayer。
[code]csharpcode: using System; using System.Collections.Generic; interface IPlayer { // 这里写的都是通用技能 void Walk(); // 一定要记得这些方法都不用加修饰符的 比如public、protected void Run(); void Shoot(); }
接下去我们就该写具体的兵种的类了
[code]csharpcode: using System; using System.Collections.Generic; class Infantry : IPlayer // 具体的兵种类都要使用这个接口 { //下面三个通用技能是必须要在这个类里面实现的,少一个都会编译错误的 public void Walk() { // 写具体的Walk方法的内容 Console.WriteLine("Infantry is walking"); } public void Run() { // 写具体的Run方法的内容 Console.WriteLine("Infantry is Running"); } public void Shoot() { // 写具体的Shoot方法的内容 Console.WriteLine("Infantry is Shooting"); } // 当把接口里的方法都实现了,我们就可以写每个职业的专属技能了,但是就算这个就算不写也是可以编译通过的哦。所以写不写就看你项目的具体情况了 public void UseRPG() { Console.WriteLine("Infantry is useRPGing"); } }
然后另外两个也照着第一个写
[code]csharpcode: using System; using System.Collections.Generic; class Tankman: IPlayer // 具体的兵种类都要使用这个接口 { //下面三个通用技能是必须要在这个类里面实现的,少一个都会编译错误的 public void Walk() { // 写具体的Walk方法的内容 Console.WriteLine("Tankman is walking"); } public void Run() { // 写具体的Run方法的内容 Console.WriteLine("Tankman is Running"); } public void Shoot() { // 写具体的Shoot方法的内容 Console.WriteLine("Tankman is Shooting"); } // 当把接口里的方法都实现了,我们就可以写每个职业的专属技能了,但是就算这个就算不写也是可以编译通过的哦。所以写不写就看你项目的具体情况了 public void DriveTank() { Console.WriteLine("Tankman is driveTanking"); } }
[code]csharpcode: using System; using System.Collections.Generic; class Medic: IPlayer // 具体的兵种类都要使用这个接口 { //下面三个通用技能是必须要在这个类里面实现的,少一个都会编译错误的 public void Walk() { // 写具体的Walk方法的内容 Console.WriteLine("Medic is walking"); } public void Run() { // 写具体的Run方法的内容 Console.WriteLine("Medic is Running"); } public void Shoot() { // 写具体的Shoot方法的内容 Console.WriteLine("Medic is Shooting"); } // 当把接口里的方法都实现了,我们就可以写每个职业的专属技能了,但是就算这个就算不写也是可以编译通过的哦。所以写不写就看你项目的具体情况了 public void Treat() { Console.WriteLine("Medic is treating"); } }
Ok,三个兵种的类搞定了,观察一下,三个兵种类有什么不同。1.类名;2.三个通用技能的内容;3.有各自的专属技能。直白的来说,这几个不同的地方你可以放心的改成你想要的内容。现在我们来使用一下这三个类。我们要三个兵种都Run一下,然后他们各自使用他们的专属技能,下面是代码:
[code]csharpcode: using System; using System.Collections.Generic; class War { static void Main(string[] args) { // 这里相当是三个玩家分别建立了三个不同兵种的角色 Infantry player0 = new Infantry(); Tankman player1 = new Tankman(); Medic player2 = new Medic(); // 然后他们都先跑了一段路 player0.Run(); player1.Run(); player2.Run(); // 玩家0使用RPG导弹;玩家1驾驶坦克;玩家2使用医疗技能 player0.UseRPG(); player1.DriveTank(); player2.Treat(); Console.ReadKey(); } }
我们来看下结果是不是按照我们也的流程来执行的
以上就是接口的简单应用了,我们来总结下:
接口的用法:
温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/69825.html