C#反射小结
2010-08-03 08:52
218 查看
今天就来一个反射的例子,主要是调用动态dll文件的,然后反射出里面的方法等,具体见下面的例子(留着自己和初学者看,呵呵):
代码
代码
using System; using System.Reflection; namespace 反射举例 { public class Program { private String file = @"反射举例.exe"; static void Main(string[] args) { Program test = new Program(); test.DisplayModules(); test.DisplayTypes(); test.DisplayMethods(); test.InvokeStaticMethod(); test.InvokeMethod(); Console.ReadLine(); } //显示所有模块名 public void DisplayModules() { Console.WriteLine("display modules ..."); Assembly assembly = Assembly.LoadFrom(file); Module[] modules = assembly.GetModules(); foreach (Module module in modules) { Console.WriteLine("module name:" + module.Name); } } //显示所有类型名 public void DisplayTypes() { Console.WriteLine("display types ..."); Assembly assembly = Assembly.LoadFrom(file); Type[] types = assembly.GetTypes(); foreach (Type type in types) { Console.WriteLine("type name:" + type.FullName); } } //先是一个类型中的所有方法名 public void DisplayMethods() { Console.WriteLine("display methods in TestReflection Type ..."); Assembly assembly = Assembly.LoadFrom(file); Type type = assembly.GetType("反射举例.Program"); MethodInfo[] methods = type.GetMethods(); foreach (MethodInfo method in methods) { Console.WriteLine("method name:" + method.Name); } } //调用一个类中的静态方法 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[] { }); } //调用一个类中的非静态方法 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"); } } }
相关文章推荐
- c#反射学习小结
- C# 反射用法小结
- C#中反射的应用小结
- C#反射技术小结
- C#中反射的应用小结
- C#中反射的应用小结
- C#中反射的应用小结
- C#中反射的应用小结
- C#反射调用其它DLL的委托事件 传值
- C#异步调用实例小结
- C# 中SqlParameter类的使用方法小结
- C#反射发出System.Reflection.Emit学习
- C#中通过反射方法获取控件类型和名称
- C#视频学习小结
- C# 反射通过类名实例化类
- C#通过反射获取对象属性,打印所有字段属性的值
- C#反射
- C#中使用反射遍历一个对象属性及值的小技巧
- C#开发WPF/Silverlight动画及游戏系列教程(Game Tutorial):(二十) 第一部分拓展小结篇
- C# Reflection反射学习