聊一聊C#接口问题 新手速来围观

2019-12-30 13:47:13王振洲

猫 


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace InterfaceProject
{
  /// <summary>
  /// 猫
  /// </summary>
  public class Cat:IAnimal
  {
    public void Shout()
    {
      Console.WriteLine("喵喵喵");
    }
  }
}

猪 


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace InterfaceProject
{
  /// <summary>
  /// 猪
  /// </summary>
  public class Pig:IAnimal
  {
    public void Shout()
    {
      Console.WriteLine("猪怎么叫来着??猪叫");
    }
  }
}

隔壁老王来实现百兽齐鸣(打倒老王这种人物的存在) 


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace InterfaceProject
{
  class Program
  {
    static void Main(string[] args)
    {
      //百兽齐鸣(这里可以使用反射来初始化所有继承IAnimal的所有动物,我就不写这个了,主要看接口)
      List<IAnimal> animals = new List<IAnimal>();
      IAnimal dog = new Dog();
      animals.Add(dog);
      IAnimal cat = new Cat();
      animals.Add(cat);
      IAnimal pig = new Pig();
      animals.Add(pig);
      //所有动物都叫一遍
      for (int i = 0; i < animals.Count; i++)
      {
        animals[i].Shout();
      }

      
    }
  }
}

我对这个接口的粗略见解就说完啦!接口这个东西虽然用起来很简单,但我们还是要理解这个接口的作用,希望我的这篇文章能够让更多像我一样的新手向接口这个东西迈出第一步。

 

注:相关教程知识阅读请移步到c#教程频道。