c# 接口

2020-12-27 06:27

阅读:417

标签:ide   string   abs   Speak   his   over   多重继承   get   wim   

帮助实现多重继承,实现不相关类的相同行为

 

定义接口

public interface IStringList

{

  void Add(string s);

  int Count {get;}

  string this[int index]{get;set};

}

//public abstract被省略了

 

接口重名时

  方法名前写接口名

    声明:void IWindow.Close(){}

    调用:((IWindow)f).Close();

 

例:

sing System;

 

interface Runner

{

void run();

}

 

interface Swimmer

{

void swim();

}

 

abstract class Animal

{

abstract public void eat();

}

 

class Person : Animal , Runner, Swimmer

{

public void run()

{

Console.WriteLine("run");

}

public void swim()

{

Console.WriteLine("swim");

}

public override void eat()

{

Console.WriteLine("eat");

}

public void speak()

{

Console.WriteLine("speak");

}

}

 

class TestInterface

{

static void m1(Runner r)

{

r.run();

}

static void m2(Swimmer s)

{

s.swim();

}

static void m3(Animal a)

{

a.eat();

}

static void m4(Person p)

{

p.speak();

}

 

public static void Main(string [] args)

{

Person p = new Person();

m1(p);

m2(p);

m3(p);

m4(p);

Runner a = new Person();

a.run();

 

}

}

 

c# 接口

标签:ide   string   abs   Speak   his   over   多重继承   get   wim   

原文地址:https://www.cnblogs.com/guomengkai/p/13347750.html


评论


亲,登录后才可以留言!