public interface ITank
{
void fire();
}
public class BigTank : ITank
{
public void fire()
{
Console.WriteLine("Big Tank fired");
}
}
2:反射 - typeof:
添加头文件:
[C#] 纯文本查看复制代码
using System.Reflection;
不知道算不算反射,视频里面讲了是讲了,但是没怎么听,把代码敲下来了,但是有太多不知道的类,加红了
public void method1()
{
RefClass refClass = new RefClass();
refClass.number = 100;
var t = refClass.GetType();
object o = Activator.CreateInstance(t);
MethodInfo run = t.GetMethod("run");
run.Invoke(o, null);
//================
Environment.Exit(0);
}
public class RefClass
{
public int number = 0;
public void run()
{
Console.WriteLine("Runnning");
Console.WriteLine(number);
}
public void jump()
{
Console.WriteLine("Jumping");
}
}
3:调用反射注入框架:
右键解决方案,管理NuGet包 - 搜索 DependencyInjection
安装Microsoft.Extensions.DependencyInjection
添加头文件
[C#] 纯文本查看复制代码
using Microsoft.Extensions.DependencyInjection;
调用例子:
[C#] 纯文本查看复制代码
public interface ITank
{
void fire();
}
public class BigTank : ITank
{
public void fire()
{
Console.WriteLine("Big Tank fired");
}
}
public class SmallTank : ITank
{
public void fire()
{
Console.WriteLine("Small Tank fired");
}
}
private void Form1_Load(object sender, EventArgs e)
{
var sc = new ServiceCollection();
sc.AddScoped(typeof(ITank), typeof(SmallTank));
var _sp_ = sc.BuildServiceProvider();
//=================================
ITank refClass = _sp_.GetService<ITank>();
refClass.fire();
//===================================
Environment.Exit(0);
}
个人理解:反射注入是基于Interface的,是对于 ITank tank = new SmallTank(); 这种的一种优化,不必要每个都改名字。