使用Activator调用同目录下文件的方法(加入反射机制)

用于生测试的类:

 

代码
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{

}

public void mymes()
{
MessageBox.Show(
"方法");
}
}

 

 

 

将上面的代码生成Dll文件 使用以下代码动态调用
代码
private void button3_Click(object sender, EventArgs e)
{
Assembly ass;
object obj;
string filep = System.Windows.Forms.Application.StartupPath + @"\Test.exe"; //获取路径
ass = Assembly.LoadFile(filep);
obj
= ass.CreateInstance("Test.Form1"); //实例化变量
Type mytype = ass.GetType("Test.Form1");
MethodInfo method
= mytype.GetMethod("mymes"); //方法名
string s = (string)method.Invoke(obj, null); //执行无参数的方法

}

 

还可以调用时带参数,在网上找到的代码如下:
代码
// System.Reflection.Assembly ass;
Type type;
//object obj;
try
{
ass
= System.Reflection.Assembly.LoadFile(@"d:\TestReflect.dll");
type
= ass.GetType("Webtest.ReflectTest");//必须使用名称空间+类名称
System.Reflection.MethodInfo method = type.GetMethod("WriteString");//方法的名称
obj = ass.CreateInstance("Webtest.ReflectTest");//必须使用名称空间+类名称
string s = (string)method.Invoke(obj, new string[] { "jianglijun" }); //实例方法的调用

Response.Write(s
+ "<br>");
method
= type.GetMethod("WriteName");//方法的名称
s = (string)method.Invoke(null, new string[] { "jianglijun" }); //静态方法的调用
Response.Write(s + "<br>");

method
= type.GetMethod("WriteNoPara");//无参数的实例方法
s = (string)method.Invoke(obj, null);
Response.Write(s
+ "<br>");
method
= null;
}
catch (Exception ex)
{
Response.Write(ex
+ "<br>");
}
finally
{
ass
= null;
type
= null;
obj
= null;
}

 

posted @ 2010-04-07 17:08  跨越高山  阅读(143)  评论(0)    收藏  举报