您的位置:首页 > 编程语言 > C#

反射 C#

2015-06-04 23:47 501 查看
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();
}
}
}


运行:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: