反正这个概念我通常都是不去记得,首先看一下什么是依赖:框架
有一个类是Animal,而后我定义了一个BlackCat类,类里面有一个BlackCat方法,那么这里的BlackCat就依赖Animal函数
public class BlackCat { public BlackCat(Animal Cat) { Cry(); } }
BlackCat类实例化的时候须要一个Animal的对象做为构造函数的参数,那么BlackCat就依赖Animal,这就叫依赖。spa
固然,不用构造函数的方式,在BlackCat类内部去new一个Animal,也是依赖;固然注入的话,就像是你写了一个类,而后code
经过IOC框架,把这个类注入到其余类中,这就是注入对象
控制反转的意思就好理解了,就好比我定义了一个类,类里面有一个方法,而后我如今要把这个方法的控制权交给别人来使用,这就是控制反转。blog
在编写代码的时候,咱们须要把一些接口编写成通用的道理就在这里了,便于作到代码复用接口
下面即以猫的例子来进行解说控制反转string
1.先定义一个动物类it
using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IOC { class Animal { public void Cry() { Console.Write("动物喊叫"); } } }
2.定义一个猫的类io
using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IOC { class Cat:Animal { public void Cry() { Console.WriteLine("动物喊叫"); } } }
3.我用实例化一个动物类,而后查看结果
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IOC { class Program { static void Main(string[] args) { Animal A = new Cat(); A.Cry(); Console.ReadLine(); } } }
4.能够看到我用子类能够替换掉父类,也能够用父类替换掉子类,其实并无太大的影响
Animal A = new Cat();
能够看见输出结果以下