接口 关键字 interface
namespace MyInterface
{
interface IFatherInterface
{
void Shout();
}
}
这边写一个接口
注意:接口中只包含成员的签名,接口没有构造函数,所以不能直接使用new对接口进行实例化。接口中只能包含方法、属性、事件和索引的组合。接口一旦被实现,实现必须实现接口中的所有的成员,除非实现类本身是抽象类
class Dog : IFatherInterface
{
public void Shout()
{
Console.WriteLine("这是狗");
}
}
这边新建一个class 继承接口 IFatherInterface
接口的定义一般以 “I” 开头 后面跟上标志性能理解的单词 因为接口里面有 Shout 方法 我们继承此接口 必要实现 接口里面 Shout方法
这边再新建两个class
class MyMethod
{
public void WriteClass(IFatherInterface item)
{
item.Shout();
Console.WriteLine("***************");
}
}
class Cat : ISonInterface
{
public void Shout()
{
Console.WriteLine("喵喵喵");
}
}
这边我们将接口作为参数传入WriteClass
class Program
{
static void Main(string[] args)
{
MyMethod p = new MyMethod();
IFatherInterface iclass;
iclass = new Dog();
p.WriteClass(iclass);
iclass = new cat();
p.WriteClass(iclass );
}
}
这边输出结果就是
如果我们cat类的功能比dog类的多的话 那我们再新建一个接口把class Cat继承于ISonInterface
interface ISonInterface: IFatherInterface
{
void aMethod();
}
class Cat : ISonInterface
{
public void aMethod()
{
Console.WriteLine("挠人");
}
public void Shout()
{
Console.WriteLine("喵喵喵");
}
}
我们这边的接口继承了接口IFatherInterface 所以 要实现IFatherInterface和ISonInterface里面的所有方法
class Program
{
static void Main(string[] args)
{
MyMethod p = new MyMethod();
IFatherInterface iclass;
ISonInterface yclass;
iclass = new Dog();
p.WriteClass(iclass);
yclass = new Cat();
p.WriteClass(yclass);
p.SayClass(yclass);
}
}
输出结果
接口作用其实就是起到一个规范的作用 举个例子
刚刚的dog类只有叫的功能 而猫类还有挠人的功能 这个时候 你叫小A去实现DOG类
叫小B去实现CAt类 这个时候 他们实现的方法什么的名字都是一样 以后维护也方便维护。