c#反射与依赖注入

反射是.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();

    }

}

比如有一个玩具,点击上面不同的动物图像发出不同的声音,但是默认的动物就几种,想在后续的时候让别的公司继续开发出不同的动物以及声音。

原文地址:https://www.cnblogs.com/anjingdian/p/13424259.html