**这是本文档旧的修订版!**
接口简介
关键字interface(int fei s)
1:接口本身不包含任何实现逻辑,它仅仅是规定了要实现它的类或结构必须遵循的蓝图。
2:接口是一种规范、只要一个类继承了接口、就要实现这个接口中的所有成员!
3:抽象类与接口都是被其他类继承\通过创建接口父类的对象来指向子类!
4:接口中的成员不允许添加访问修饰符,默认就是public
5:接口与接口之间可以继承、且可以多继承、
6: 接口不能去继承一个类、而类可以继承接口、
9:为了多态、接口不能被new实例化!
但可以用来定义变量、以便用来引用、继承的子类成员、例如:
class Program //正常不这样用但需要了解
{
static void Main(string[] args)
{
// 使用接口类型的变量来引用实现了接口的对象
IAnimal myDog = new Dog();
// 调用接口的方法,实际执行的是具体对象的方法
myDog.MakeSound(); // 输出 "Woof!"
}
}
// 定义一个接口
interface IAnimal
{
void MakeSound();
}
// 继承于接口的Dog类
class Dog : IAnimal
{
public void MakeSound()//实现接口的方法
{
Console.WriteLine("im_Dog !");
}
}
接口举例1
接口是一种规范、只要一个类继承了接口、就要实现这个接口中的所有成员!
class Program
{
static void Main(string[] args)
{ //实例化派生类
class_get_Information syong = new class_get_Information();
//使用
syong.Name = "手机";
syong.Codr = "00254";
syong.ShowInfo();
}
}
//接口
interface Information
{
string Codr { get; } //接口中的成员变量
string Name { get; } //接口中的成员变量
void ShowInfo();//接口中的成员函数
}
//自定义派生类[继承]
public class class_get_Information : Information
{
string str_1 = "" ;
string str_2 = "";
public string Codr
{
get
{
return str_1;
}
}
public string Name
{
get
{
return str_2;
}
}
public void ShowInfo() //实现接口成员的函数
{
//实现的方法//自定义
}
}
接口举例2
接口的多态举例
using System;
class Program
{
static void Main(string[] args)
{
// 使用接口类型的变量来引用实现了接口的对象
IAnimal myDog = new Dog();
IAnimal myCat = new Cat();
// 调用接口的方法,实际执行的是具体对象的方法
myDog.MakeSound(); // 输出 "Woof!"
myCat.MakeSound(); // 输出 "Meow!"
}
}
// 定义一个接口
interface IAnimal
{
void MakeSound();
}
// 继承于接口的类Dog
class Dog : IAnimal
{
public void MakeSound()//实现接口的方法
{
Console.WriteLine("im_Dog !");
}
}
// 继承于接口的类Cat
class Cat : IAnimal
{
public void MakeSound()//实现接口的方法
{
Console.WriteLine("im_Cat !");
}
}
总接:一个/多个类继承了接口、
就可以用接口定义的变量来引用[点]子类里面实现接口成员的函数、

