C#自学——接口类

C#自学——接口类

编码文章call10242025-01-10 13:58:0219A+A-
// 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

点击这里复制本文地址 以上内容由文彬编程网整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!
qrcode

文彬编程网 © All Rights Reserved.  蜀ICP备2024111239号-4