1.写一个类,编译成dll
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ReflectTest
{
public class TestClass
{
public int Totalizator(int a,int b)
{
return a + b;
}
}
}
3.反射调用dll中的方法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
namespace ExamplePro
{
class Program
{
static void Main(string[] args)
{
//从Dll中加载
Assembly ass = Assembly.LoadFile(@"E:\Project\Dll\ReflectTest.dll");
//获取类型
Type Cltype= ass.GetType("ReflectTest.TestClass");
object reflectObj = Activator.CreateInstance(Cltype,null);
//使用MethodInfo 和Invoke 调用方法
MethodInfo displayInfoMethod = Cltype.GetMethod("Totalizator");
object data= displayInfoMethod.Invoke(reflectObj, new object[] {1,2});
int intData = Int32.Parse(data.ToString());
Console.WriteLine("反射调用Totalizator方法得到:" + intData.ToString());
Console.ReadKey();
}
}
}
运行: