反正這個概念我通常都是不去記得,首先看一下什麼是依賴:框架
有一個類是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();
能夠看見輸出結果以下