标签:
前言: 完全是我在学习过程中记录的笔记,只不过分享一下让很多刚开始学习.net编程的人能够很快的学会C#语言
(1) 有时候需要考虑子类中一部分具有某些能力(方法),同时又需要考虑其多态的特征,这时候可以考虑接口
(2)语法:
public interface 接口名
{
//成员
}
(3) 接口的存在就是为了被实现
(4)有了接口以后实现该接口的子类可以赋值给这个接口的变量,就可以实现多态了
(5)接口的存在就是为了多态
(6)接口与类的其中一个不同点在于多"继承"(实现)
(7)接口的使用
interface IDriveable
{
void Dirving();
}
class Teacher : IDriveable
{
public void Dirving()
{
Console.WriteLine("终于有驾驶证了");
}
}
class Program
{
static void Main(string[] args)
{
Teacher th = new Teacher();
th.Dirving();
IDriveable dir = th;
dir.Dirving();
}
}
(8)接口的补充
1)接口中的方法
->默认接口成员均是public,所以不需要考虑访问修饰符
->直接不写访问修饰符
返回值 方法名 (参数);
2)接口的思想类中实现方法的语法:方法该怎么写就怎么写,好像没有接口存在一样
3)接口的实现类必须实现接口中的成员
4)接口中可以有哪些成员:抽象成员
(9)在使用上接口与抽象类非常类似(但是接口不允许有非抽象成员,成员的语法定义不同,多继承)
(10)在继承中有接口,又有类的时候注意:
1)语法
class 类名:父类,接口,接口
{
//成员
}
2)多个接口中如果有重名方法怎么办?
->使用显示实现接口的方式
->方法名是有接口名引导的
->方法没有访问修饰符
->方法不能被该类型的实例对象说调用,必须将其转换为接口类型进行调用
接口的实现
interface Iinter1
{
void Func();
}
interface Iinter2
{
void Func();
}
class MyClass : Iinter1, Iinter2
{
void Iinter1.Func()
{
Console.WriteLine("接口1");
}
void Iinter2.Func()
{
Console.WriteLine("接口2");
}
}
class Program
{
static void Main(string[] args)
{
MyClass m = new MyClass();
Iinter1 i1 = m;
i1.Func();
Iinter2 i2 = m;
i2.Func();
}
}
1 interface Iinter1
2
3 {
4
5 void Func();
6
7 }
8
9 interface Iinter2
10
11 {
12
13 void Func();
14
15 }
16
17 class MyClass : Iinter1, Iinter2
18
19 {
20
21 void Iinter1.Func()
22
23 {
24
25 Console.WriteLine("接口1");
26
27 }
28
29 void Iinter2.Func()
30
31 {
32
33 Console.WriteLine("接口2");
34
35 }
36
37 }
38
39 class Program
40
41 {
42
43 static void Main(string[] args)
44
45 {
46
47 MyClass m = new MyClass();
48
49 Iinter1 i1 = m;
50
51 i1.Func();
52
53 Iinter2 i2 = m;
54
55 i2.Func();
56
57 }
58
59 }
接口实现暗黑游戏的一点山寨
(1) 首先新建一个控制台应用程序,自己随便起个名字
(2)在新建一个接口,起名为interfaceModel,这个接口实现了攻击的种类
interface IFile //火系攻击
{
void Fight();
}
interface IIce //冰系攻击
{
void Fight();
}
(3)其次新建一个可以实现所有攻击方法的类
/// <summary>
/// 一个可以实现所有方法的类
/// </summary>
abstract class Person
{
public abstract void Gongji();
}
(4)新建一个fashi类,此类实现了法师的所有的攻击手段
abstract class fashi : Person
{
}
class fashi1 : fashi, IFile
{
public void Fight()
{
Console.WriteLine("火攻");
}
public override void Gongji()
{
Fight();
}
}
class fashi2 : fashi, IIce
{
public void Fight()
{
Console.WriteLine("冰攻");
}
public override void Gongji()
{
Fight();
}
}
class fashi3 : fashi, IFile, IIce
{
public override void Gongji()
{
//随机的攻击
Random rand = new Random();
if (rand.Next() % 2 == 0)
{
IIce i = this as IIce;
i.Fight();
}
else
{
(this as IFile).Fight();
}
}
void IFile.Fight()
{
Console.WriteLine("火攻");
}
void IIce.Fight()
{
Console.WriteLine("冰攻");
}
}
(5)在main方法中实现如下函数
static void Main(string[] args)
{
fashi f = new fashi3();
while (true)
{
f.Gongji();
Console.ReadKey();
}
}
(6)在定义方法的时候,可以为变量赋初值,该值为默认值,如果不传参数就默认使用这个值,如果传参,使用传进来的参数替代这个值
(7)微软推荐使用默认参数而非重载
标签:
原文地址:http://www.cnblogs.com/yuqlblog/p/4891015.html