在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
一、接口可以干嘛 我们知道,接口的本质是一个约束规范,委托是方法纵向(形式上)的封装,接口是不同方法横向(广度)的封装 接口中不能有变量,但是可以有属性方法。常见的,我们可以用接口: 1、实现需求方的方法 2、接口作为参数,实现对不同类的解耦,下面是常见的男女类 public interface ISay { void Say(); } public class Man:ISay { public void Say() { Console.WriteLine("你好,我是男士!"); } } public class Woman : ISay { public void Say() { Console.WriteLine("你好,我是女士!"); } } public class Peole { public void Say(ISay iPeople) { iPeople.Say(); } } class Program { static void Main(string[] args) { Man man = new Man(); Woman woman = new Woman(); Peole peole = new Peole(); peole.Say(man); peole.Say(woman); Console.ReadLine(); } } 3、接口作返回值,返回一个实现了接口的对象,基本和上面的例子类似 二、接口可以传参(常用来做对外SDK) 下面以两种常见构型讲解 1、A工厂生产产品,B工厂代理,C工厂卖,于是我们: public interface ITransfer { void Transfer(string msg); } public class FactoryA { public ITransfer FacATransfer = null; public FactoryA() { product(); } public void product() { int produceNum=0; Task.Factory.StartNew(()=> { while (true) { produceNum++; FacATransfer?.Transfer(String.Format("来自FactoryA的第{0}个产品", produceNum)); Thread.Sleep(2000); } }); } } public class FactoryB //中间商 { public void ConnectInit(ITransfer transfer) { FactoryA factoryA = new FactoryA(); factoryA.FacATransfer = transfer; } } public class FactoryC:ITransfer { public FactoryC() { FactoryB factoryB = new FactoryB(); factoryB.ConnectInit(this); } public void Transfer(string msg) { Console.WriteLine("为FactoryC生产,"+msg); } } 调用 class Program { static void Main(string[] args) { FactoryC factoryC = new FactoryC(); //FactoryD factoryD = new FactoryD(); Console.ReadLine(); } } 2、工厂A生产,D直接代理 public class FactoryA { public ITransfer FacATransfer = null; public FactoryA() { product(); } public void product() { int produceNum=0; Task.Factory.StartNew(()=> { while (true) { produceNum++; FacATransfer?.Transfer(String.Format("来自FactoryA的第{0}个产品", produceNum)); Thread.Sleep(2000); } }); } } 调用: class Program { static void Main(string[] args) { //FactoryC factoryC = new FactoryC(); FactoryD factoryD = new FactoryD(); Console.ReadLine(); } } 学习请加qq群:568055323
|
请发表评论