反射 C#

来源:互联网 发布:tomcat下js文件未生效 编辑:程序博客网 时间:2024/06/08 14:26

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;        }    }}


2.编译成dll取出,放在E:\Project\Dll目录下,取名:ReflectTest.dll

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();        }    }}


运行:


0 0