code show as below:
Using system.reflection; using system.reflection.emit;
Public class testReflection {private string file = @ "testReflection.exe";
static void Main (String [] args) {TestReflection test = new TestReflection (); test.DisplayModules (); test.DisplayTypes (); test.DisplayMethods (); test.InvokeStaticMethod (); test.InvokeMethod ();} / / Show all module names public void DisplayModules () {Console.WriteLine ( "display modules ..."); Assembly assembly = Assembly.LoadFrom (file); module [] modules = assembly.GetModules (); foreach (module module in {Console.Writeline ("Module Name:" Module.Name);}} // Displays all types of public void displaytypes () {console.writeline ("Display Types ..."); assembly assmbly = askEMBLY. LoadFrom (file); type [] types = askEMBLY.GETTYPES (); foreach (type type in type) {console.writeline ("Type Name:" type.FullName);}} // is a type in all methods name public void DisplayMethods () {Console.WriteLine ( "display methods in TestReflection Type ..."); Assembly assembly = Assembly.LoadFrom (file); Type type = assembly.GetType ( "TestReflection"); MethodInfo [] methods = TYPE.GETMETHODS (); foreach (MethodInfo Method in methods) {console.writeline ("Method name:" method.name);}} // call a static method in a class PUBLIC VOID InvokeStaticMethod () {Console.Writeline ("Invoke Static Method ...") ; Assembly assembly = Assembly.LoadFrom (file); type type = assembly.GetType ( "TestSubClass"); type.InvokeMember ( "SayHello", BindingFlags.InvokeMethod, null, null, new object [] {});} // calling a class of non-static method public void InvokeMethod () {Console.WriteLine ( "invoke method ..."); Assembly assembly = Assembly.LoadFrom (file); type type = assembly.GetType ( "TestSubClass"); Object Obj = activator.createInstance (TYPE);
TestClass tc = (TestClass) obj; type.InvokeMember ( "Test1", BindingFlags.InvokeMethod, null, tc, new object [] {}); type.InvokeMember ( "Test2", BindingFlags.InvokeMethod, null, tc, new object [] {});}} Public interface testclass {void test1 (); void test2 ();} public class testsubclass: testclass {public void test1 () {console.writeline ("this is testsubclass.test1);} PUBLIC Void test2 () {console.writeline ("this is testsubclass.test2");} public static void sayhello () {console.writeLine ("this is testsubclass.sayhello);}} After compiling operation:
display modules ... module name: TestReflection.exedisplay types ... type name: TestReflectiontype name: TestClasstype name: TestSubClassdisplay methods in TestReflection Type ... method name: GetHashCodemethod name: Equalsmethod name: ToStringmethod name: DisplayModulesmethod name: DisplayTypesmethod name: DisplayMethodsmethod name: InvokeStaticMethodmethod name: InvokeMethodmethod name: Test2method name: GetTypeInvoke static method ... This is TestSubClass.SayHelloInvoke Method ... This is TestSubClass.Test1This is TestSubClass.Test2