最近复习知识发现自己在C#反射这块搞得不是很清楚,查了很多资料,发现讲原理讲的多,举的示例都很复杂,自己研究了半天,总结出用1个简单的小示例作为从出发点:
便于对反射使用方法的记忆,掌握了基本使用方法也更有利于举一反三,学习未来可能遇到的高级用法
dll动态加载流程
0.准备测试用例
0.1
0.2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test_dll
{
public class test
{
public int testNum = 233;
public string testMsg { get; set; }
public int Add(int a,int b)
{
return a + b;
}
}
}
0.3 将Test_dll编译为dll文件(右键->属性)
1.设置dll路径并加载:
string path = @"D:\xxxx\Test_Reflection\Test_dll\bin\Debug\Test_dll.dll";
Assembly assembly = Assembly.LoadFile(path);
2.获取类的类型(命名空间.类->只写类名会报错)
Type typeTest = assembly.GetType("Test_dll.test");
3.创建类的实例(类似于new1个实例)
object newInstance = Activator.CreateInstance(typeTest);
4.获取方法、字段、属性等(这里获取的不是值,只是定义)
//方法
MethodInfo method_Add = typeTest.GetMethod("Add");
//字段
FieldInfo fieldInfo = typeTest.GetField("testNum");
//属性
PropertyInfo propertyInfo = typeTest.GetProperty("testMsg");
5.(在上一步基础上)获取值、调用方法
//获取字段值
int temp = (int)fieldInfo.GetValue(newInstance);
//设置属性值
propertyInfo.SetValue(newInstance, "Hello呀");
//调用方法->Invoke(实例名,参数列表)
int method_Result = (int)method_Add.Invoke(newInstance, new object[] { 1, 9 });
6.结果测试
Console.WriteLine("属性值: "+propertyInfo.GetValue(newInstance));
Console.WriteLine("字段值: " + temp);
Console.WriteLine("调用方法的返回值: " + method_Result);
引申用法
- 将上文测试中的路径地址、dll名等封装在配置文件中
<appSettings>
<add key="typeTest" value="Test_dll.test,Test_dll"/>
</appSettings>
- 在程序中解析配置
private static string dllType = ConfigurationManager.AppSettings["typeTest"];
private static string dllName = dllType.Split(',')[1];
private static string typeNme = dllType.Split(',')[0];