C#依赖注入简单代码举例:
没有讲解,只是自己简单实现:
using System;
namespace Inject
{
interface ISay{
void Say();
void Eat(int num);
}
class CSay : ISay
{
public void Eat(int num)
{
Console.WriteLine("CEat" + num);
}
public void Say()
{
Console.WriteLine("CSay");
}
}
class USay : ISay
{
public void Eat(int num)
{
Console.WriteLine("UEat" + num);
}
public void Say()
{
Console.WriteLine("USay");
}
}
internal class Factory : ISay
{
ISay iSay;
public Factory(ISay iSay)
{
this.iSay = iSay;
}
public void Say()
{
iSay.Say();
}
public void Eat(int num)
{
iSay.Eat(num);
}
}
class Program
{
static void Main(string[] args)
{
CSay cSay = new CSay();
cSay.Say();
cSay.Eat(2);
//使用了依赖注入
ISay iSay = new CSay();
Factory factory = new Factory(iSay);
factory.Say();
factory.Eat(2);
Console.ReadLine();
}
}
}