反射是.net框架的功能,不只是c#語言的功能。
依賴反轉是一個概念,但是依賴注入是在概念基礎之上結合接口和反射機制所形成的應用。
依賴注入最重要的是有一個container容器,各種各樣的類型和對應的接口都放到容器里面,在.NET Freamwork中,有一個第三方容器Unity, 但是在.NET Core里面,是IServiceCollection。
下面是簡單依賴注入的方法
namespace TestClass { class Program { static void Main(string[] args) { //var driver = new Driver(new LightTank()); //driver.Run(); #region 這是可以在程序啟動的時候注冊的方式 //創建容器對象 var sc = new ServiceCollection(); //往容器中裝數據接口是IItank,實現這個接口的是LightTank, sc.AddScoped(typeof(IItank), typeof(LightTank)); sc.AddScoped(typeof(IVehicle),typeof(Car)); sc.AddScoped<Driver>() ; var sp = sc.BuildServiceProvider(); #endregion #region 這是在程序其他地方只要能獲取到sp對象的地方就能用 IItank itank = sp.GetService<IItank>(); //因為在注冊的時候實現的是LightTank,所以下列的方法全是執行這個類的方法 itank.Fire(); itank.Run(); //因為注冊的交通工具是Car,所以這里調用的就是Car類的方法 var driver = sp.GetService<Driver>(); driver.Run(); #endregion Console.ReadKey(); } } interface IVehicle { void Run(); } /// <summary> /// 汽車 /// </summary> class Car : IVehicle { public void Run() { Console.WriteLine("Car is running"); } } /// <summary> /// 卡車 /// </summary> class Truck : IVehicle { public void Run() { Console.WriteLine("Truck is running"); } } /// <summary> /// 坦克 /// c#中類或者接口可以繼承多接口,但是不能繼承多基類。 /// /// </summary> interface IItank : IVehicle, IWeapon { } class LightTank : IItank { public void Fire() { Console.WriteLine("LightTank is firing"); } public void Run() { Console.WriteLine("LightTank is running"); } } class HeavyTank : IItank { public void Fire() { Console.WriteLine("HeavyTank is firing"); } public void Run() { Console.WriteLine("HeavyTank is running"); } } /// <summary> /// 駕駛員類 /// </summary> class Driver { private IVehicle vehicle; public Driver(IVehicle vehicle) { this.vehicle = vehicle; } public void Run() { vehicle.Run(); } } interface IWeapon { void Fire(); } }