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"); } } }使用命令行编译csc /t:library ReflectTest.cs命令进行编译,生成ReflectTest.dll库文件。然后进行下列程序的编写:using System; using System.Reflection;
class TestApp { public static void Main() { Assembly ass; Type type; Object obj;
//Used to test the static method Object any = new Object();
//Load the dll //Must indicates the whole path of dll ass = Assembly.LoadFile(@"D:Source Code 0.C# Sudy 1.Reflection 1ReflectTest.dll"); //Must be Namespace with class name type = ass.GetType("ReflectionTest.WriteTest");
//Since the WriteTest Class is not Static you should Create the instance of this class obj = ass.CreateInstance("ReflectionTest.WriteTest");
method.Invoke( obj,//Instance object of the class need to be reflect parametors);//Parametors of indicated method
//method.Invoke(any, parametors);//RuntimeError: class reference is wrong
/**//*example2----------*/
method = type.GetMethod("StaticWriteString");
//The first parametor will be ignored method.Invoke(null, new string[] { "test"}); method.Invoke(obj, new string[] { "test"});//indicates the instance will equals above line method.Invoke(any, new string[] { "test"});//Even the class reference is wrong
/**//*example3-----------*/
method = type.GetMethod("NoneParaWriteString");
//Sine the method NoneParaWriteString()
has no parametors so do not indicate any parametors method.Invoke(null, null);