C#自学——接口类
// interface -- 接口类关键词,接口类默认的访问修饰符是 public
// 接口的命名方式 大写I 开头
// 接口类提出需求,派生类实现需求
interface IAction
{
// 下面的都是需要派生类实现的方法,将方法具体化
void Run();
void Eat();
}
class Animal : IAction
{
// 接口里面存在的方法都必须存在,可以不用但不能没有
public void Run()
{
Console.WriteLine("这是Run方法的具体的实现");
}
public void Eat()
{
Console.WriteLine();
}
}
class Print
{
static void Main()
{
Animal animal = new Animal();
animal.Run();
animal.Eat();
}
}
输出:
这是Run方法的具体的实现 // 这是实现出来的Run
// 这是实现出来的Eat,因为 Console.WriteLine() 输出后会自动换行,所以这会有一行空白
interface IAction
{
void Run();
void Eat();
}
interface IPorperty
{
string[] Info(string name, int age);
void Print();
}
class Dog
{
}
// 可以继承多个接口,每个接口的方法都必须存在
// 昨天的继承只能继承一个,不能继承多个
// 需要继承的类只能写在接口前面
class Animal : Dog,IAction,IPorperty
{
public void Run()
{
Console.WriteLine("这是Run方法的具体的实现");
}
public void Eat()
{
Console.WriteLine();
}
public string[] Info(string name, int age)
{
return new string[] { name, age + "" };
}
public void Print()
{
string[] info = Info("包子",3);
Console.WriteLine("name: {0}\tage: {1}", info[0], info[1]);
}
}
class Print
{
static void Main()
{
Animal animal = new Animal();
animal.Run();
animal.Eat();
animal.Print();
}
}
输出:
这是Run方法的具体的实现 // 这是实现出来的Run
// 这是实现出来的Eat,因为 Console.WriteLine() 输出后会自动换行,所以这会有一行空白
name: 包子 age: 3 // 这是实现出来的Print
上一篇:1-4、类-属性_笔记
下一篇:【2.C#基础】9.类