C#反射的使用
1、先定义个类,编译成dll,用于调用
nameSpace Test
{
public class Class1 { private string _name; private int _age; public Class1(string name,int age) { _name = name; _age = age; } public void ChangeName(string newName) { _name = newName; } public void ChangeAge(int newAge) { _age = newAge; } public override string ToString() { return string.Format("Name:{0},Age:{1}", _name, _age); } }
}
2、测试调用。读取dll中的属性和方法,赋值,并得到输出结果。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; namespace TestApp { class Program { static void Main(string[] args) { //获取dll程序集 Assembly tmpAss = Assembly.LoadFile(AppDomain.CurrentDomain.BaseDirectory + "Test.dll"); //获取程序集所有类型 Type[] tmpTypes = tmpAss.GetTypes(); foreach (Type tmpType in tmpTypes) { //获取程序集中的构造函数 ConstructorInfo[] tmpInfors = tmpType.GetConstructors(); foreach (ConstructorInfo tmpInfo in tmpInfors) { //获取构造函数的参数 ParameterInfo[] tmpParamInfos = tmpInfo.GetParameters(); object[] tmpParams = new object[tmpParamInfos.Length]; for (int i = 0; i < tmpParamInfos.Length; i++) { //判断参数类型并赋值 tmpParams[i] = tmpAss.CreateInstance(tmpParamInfos[i].ParameterType.FullName); if (tmpParamInfos[i].ParameterType.FullName == "System.String") { tmpParams[i] = "Clint"; } } object tmpObj = tmpInfo.Invoke(tmpParams); Console.WriteLine(tmpObj); //获取程序集中的方法 foreach (MethodInfo tmpMethod in tmpType.GetMethods()) { tmpParamInfos = tmpMethod.GetParameters(); tmpParams = new object[tmpParamInfos.Length]; for (int i = 0; i < tmpParamInfos.Length; i++) { //判断参数类型并赋值 tmpParams[i] = tmpAss.CreateInstance(tmpParamInfos[i].ParameterType.FullName); if (tmpParamInfos[i].ParameterType.FullName == "System.String") { tmpParams[i] = "Clint Su"; } if (tmpParamInfos[i].ParameterType.FullName == "System.Int32") { tmpParams[i] = 27; } } tmpMethod.Invoke(tmpObj, tmpParams); } Console.WriteLine(tmpObj); } Console.ReadLine(); } } } }
输出结果:
Name:Clint,Age:0
Name:Clint Su,Age:27