您的位置:首页 > 其它

反射dll里的函数

2016-04-21 10:50 239 查看
生成dll的程序
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ReflectionTest
{
public class WriteTest
{
//public method with parametors
public void WriteString(string s, int i)
{
Console.WriteLine("WriteString:" + s + i.ToString());
}

//static method with only one parametor
public static void StaticWriteString(string s)
{
Console.WriteLine("StaticWriteString:" + s);
}

//static method with no parametor
public static void NoneParaWriteString()
{
Console.WriteLine("NoParaWriteString");
}
}
}
反射调用dll函数的程序
<pre name="code" class="csharp">using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Reflection;class TestApp{public static void Main(){Assembly ass;Type type;Object obj;Object any = new Object();ass = Assembly.LoadFile(@"F:\1Test\ReflectTest\ReflectTest\bin\Debug\ReflectTest.dll");//dll文件的绝对路径type = ass.GetType("ReflectionTest.WriteTest");//命名空间.类名/*example1---------*/MethodInfo method = type.GetMethod("WriteString");string test = "test";int i = 1;Object[] parametors = new Object[] { test, i };obj = ass.CreateInstance("ReflectionTest.WriteTest");method.Invoke(obj,//Instance object of the class need to be reflectparametors);//method.Invoke(any, parametors);//RuntimeError: class reference is wrong/*example2----------*/method = type.GetMethod("StaticWriteString");method.Invoke(null, new string[] { "test" });method.Invoke(obj, new string[] { "test" });method.Invoke(any, new string[] { "test" });/*example3-----------*/method = type.GetMethod("NoneParaWriteString");method.Invoke(null, null);}}
备注
调用时不需要引用dll文件 http://blog.csdn.net/bdstjk/article/details/7535230 例子1种必须实例化反射要反射的类,因为要使用的方法并不是静态方法例子2种我们想用的方法是一个静态方法,这时候Invoke的时候,对于第一个参数是无视的第三个例子是一个调用无参数静态方法的例子,这时候两个参数我们都不需要指定,用null就可以了
                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: