反射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就可以了
相关文章推荐
- 使用 jar命令 简单的修改 jar包
- CombineMeshes
- [IOS/翻译]Media Layer
- c++第四次实验 -利用循环求和
- 解决端口被占用的问题
- Webpack 性能优化 (一)(使用别名做重定向)
- C++常考面试题
- 基于opencv和QT的人脸(人眼)检测程序
- php开发中的页面跳转方法
- 软键盘弹出布局与edittext一起上移
- 流程实例管理
- iOS语音播放之切换听筒和扬声器的方法解决方案
- Android 用户界面---操作栏(Action Bar 一)
- [IOS/翻译]Core Services Layer
- C++实验2-利用循环求和
- 战斗预判
- App架构设计经验谈:技术选型
- [财经评] 房市退烧,能迎来股市的春天吗?
- 敲响OO时代的丧钟
- Chrome谷歌浏览器下不支持css字体小于12px的解决办法