反射与依赖注入
作者:互联网
反射(松耦合-以不变应万变)
不用new 操作符都能创建同类型的对象,访问对象的各个成员,有new操作符是有类型依赖的。
程序在运行时处于动态,不能随便改变类型,但是不清楚用户可能的操作,所以让程序在静态时就做好准备,但是又不是枚举每种类型。
using System;
using System.Reflection;
namespace Driver_core
{
internal class Program
{
public static void Main(string[] args)
{
ITank tank=new LightTank();
//不用静态类型
var t=tank.GetType();//得到运行时动态类型的描述信息
object o= Activator.CreateInstance(t);
MethodInfo fire = t.GetMethod("Fire");
MethodInfo run = t.GetMethod("Run");
fire.Invoke(o, null);
run.Invoke(o, null);
}
}
class Driver
{
private IVehicle _vehicle;
public Driver(IVehicle vehicle)
{
_vehicle = vehicle;
}
public void Drive()
{
_vehicle.Run();
}
}
interface IVehicle
{
void Run();
}
class Car:IVehicle
{
public void Run()
{
Console.WriteLine("car is runnning!");
}
}
class Truck:IVehicle
{
public void Run()
{
Console.WriteLine("truck is running!");
}
}
interface ITank
{
void Fire();
void Run();
}
class LightTank:ITank
{
public void Fire()
{
Console.WriteLine("开炮");
}
public void Run()
{
Console.WriteLine("ka……ka……ka");
}
}
}
反射与接口的集合
反射与特性的集合
依赖注入
封装好的反射。
引入denpendinjection 依赖
using System;
using System.Reflection;
using Microsoft.Extensions.DependencyInjection;
namespace Driver_core
{
internal class Program
{
public static void Main(string[] args)
{
var sc=new ServiceCollection();//服务提供者(容器)
sc.AddScoped(typeof(ITank),typeof(LightTank));//基接口动态类型描述,实现的类的类型
var sp = sc.BuildServiceProvider();
//从容器里去调用对象
ITank tank = sp.GetService<ITank>();
tank.Fire();
tank.Run();
}
}
class Driver
{
private IVehicle _vehicle;
public Driver(IVehicle vehicle)
{
_vehicle = vehicle;
}
public void Drive()
{
_vehicle.Run();
}
}
interface IVehicle
{
void Run();
}
class Car:IVehicle
{
public void Run()
{
Console.WriteLine("car is runnning!");
}
}
class Truck:IVehicle
{
public void Run()
{
Console.WriteLine("truck is running!");
}
}
interface ITank
{
void Fire();
void Run();
}
class LightTank:ITank
{
public void Fire()
{
Console.WriteLine("开炮");
}
public void Run()
{
Console.WriteLine("ka……ka……ka");
}
}
}
标签:反射,依赖,Run,void,class,vehicle,IVehicle,public,注入 来源: https://www.cnblogs.com/lpxspring/p/12461539.html