生成dll的程序
备注
调用时不需要引用dll文件
http://blog.csdn.net/bdstjk/article/details/7535230
例子1种必须实例化反射要反射的类,因为要使用的方法并不是静态方法
例子2种我们想用的方法是一个静态方法,这时候Invoke的时候,对于第一个参数是无视的
第三个例子是一个调用无参数静态方法的例子,这时候两个参数我们都不需要指定,用null就可以了
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 reflect parametors); //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就可以了