反正这个概念我一般都是不去记得,首先看一下什么是依赖:
有一个类是Animal,然后我定义了一个BlackCat类,类里面有一个BlackCat方法,那么这里的BlackCat就依赖Animal
public class BlackCat
{
public BlackCat(Animal Cat)
{
Cry();
}
}
BlackCat类实例化的时候需要一个Animal的对象作为构造函数的参数,那么BlackCat就依赖Animal,这就叫依赖。
当然,不用构造函数的方式,在BlackCat类内部去new一个Animal,也是依赖;当然注入的话,就像是你写了一个类,然后
通过IOC框架,把这个类注入到其他类中,这就是注入
控制反转的意思就好理解了,就比如我定义了一个类,类里面有一个方法,然后我现在要把这个方法的控制权交给别人来使用,这就是控制反转。
在编写代码的时候,我们需要把一些接口编写成通用的道理就在这里了,便于做到代码复用
下面即以猫的例子来进行解说控制反转
1.先定义一个动物类
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IOC
{
class Animal
{
public void Cry()
{
Console.Write("动物喊叫");
}
}
}
2.定义一个猫的类
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();
可以看见输出结果如下
