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


这段时间的项目有用到接口,开始不是特别理解接口,只是单单知道接口定义非常简单,甚至觉得这个接口只是多此一举(个人开发的时候)。现在开始团队开发,才发现接口原来是这么的重要和便捷! 

接下来就来谈谈我这段时间对接口使用的粗浅见解,说的对希望大家赞,说的有误的地方希望大家多多包涵建议! 

READY GO! 

接口的定义就不多说了,它有一个很重要的知识点,就是所有继承这个接口类的都必须实现接口中的定义,说到这个必须,在团队开发中,只要我们商定好了接口,那我们的代码是不是就统一了!!! 

这是我觉得接口重要的第一点:它便于我们统一项目的规定,便于团队代码的管理!

再来用一个例子说明: 

A公司决定开发一套动物系统,其中包含很多的动物,公司决定要实现每个动物的喊叫行为……
说到这里,我们一般就是各个程序员拿到自己要实现的动物类之后就开始大刀阔斧的开干了!!!
X程序员实现狗这个类,他写一个叫喊方法void Han(){……}
Y程序员实现猫这个类,他写一个叫喊方法void Shout(){……}
M程序员实现猪这个类,他写一个叫喊方法 void Shout(string content){……} 
……………… 

好了,现在都完成了各自需要完成的动物,隔壁老王开始来实现百兽齐鸣!!!!&¥%¥*%¥¥%¥一顿粗口爆出!这要怎么写?一个个去调用??? 

来看看,X程序员英语不太好,也没有过多的去管,只是写出动物叫喊的方法,Y程序员和M程序员写的叫喊方法名称是一样,但M程序员中还要传递动物叫喊的内容!!!!! 

隔壁老王现在要让所有动物都叫一遍就得一个动物一个动物的去调用方法…… 

OK,接下来开会商量,隔壁老王定义一个动物接口,所有的动物类都得继承这个接口,这个接口只定义一个void Shout();  (就不过多的写东西啦,偷偷懒) 

X,Y,M程序员继承后,X,M立马就发现有问题,然后开始改了自己手中的类 

这时老王就开始来百兽齐鸣啦!哈哈哈哈哈 

接下来贴出代码大家看 

接口 

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

namespace InterfaceProject
{
  /// <summary>
  /// 动物接口
  /// </summary>
  interface IAnimal
  {
    /// <summary>
    /// 动物叫喊
    /// </summary>
    void Shout();
  }
}

狗 

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

namespace InterfaceProject
{
  /// <summary>
  /// 狗
  /// </summary>
  public class Dog: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 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();
      }

      
    }
  }
}

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


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3