如果你采用汽车的经典例子.您可以通过常规汽车购买流程并采取制造商为您提供的轮子:
public class Fifteens
{
public void Roll() { Console.WriteLine("Nice smooth family ride..."); }
}
public class Car
{
Fifteens wheels = new Fifteens();
public Car() { }
public void Drive() { wheels.Roll; }
}
Run Code Online (Sandbox Code Playgroud)
然后:
Car myCar = new Car();
myCar.Drive() // Uses the stock wheels
Run Code Online (Sandbox Code Playgroud)
或者您可以找到一个自定义的Car构建器,它允许您准确指定您希望Car使用哪种类型的车轮,只要它们符合车轮的规格:
public interface IWheel
{
void Roll();
}
public class Twenties : IWheel
{
public void Roll() { Console.WriteLine("Rough Ridin'...");
}
public class Car
{
IWheel _wheels;
public Car(IWheel wheels) { _wheels = wheels; }
public void Drive() { wheels.Roll(); }
}
Run Code Online (Sandbox Code Playgroud)
然后:
Car myCar = new Car(new Twenties());
myCar.Drive(); // Uses the wheels you injected.
Run Code Online (Sandbox Code Playgroud)
但是现在你可以注入你想要的任何类型的轮子.请记住,他只是一种依赖注入(构造函数注入),但它是最简单的示例之一.