- 新建两个项目:类库(Model)和控制台应用程序(ReflectTest)。
- 在【Model】中添加一个类【User】:
1 namespace Model 2 { 3 public class User 4 { 5 public string Show() 6 { 7 return "Test Reflect."; 8 } 9 } 10 }
- 编译生成【Model】,并把生成的dll拷贝到【ReflectTest】项目下的【\bin\Debug\】文件夹里面。
- 实现反射:
1 using System; 2 using System.Reflection; 3 4 namespace ReflectTest 5 { 6 class Program 7 { 8 static void Main(string[] args) 9 { 10 Assembly assembly = Assembly.Load("Model"); // 1. 动态加载dll 11 Type userType = assembly.GetType("Model.User"); // 2. 找到具体类型 12 object instance = Activator.CreateInstance(userType); // 3. 给类型创建一个对象 13 14 // 解析dll 15 { 16 // 获取程序集中的所有类型 17 foreach (Type type in assembly.GetTypes()) 18 { 19 Console.WriteLine(type.Name); 20 } 21 22 // 获取类型中所有方法 23 foreach (MethodInfo method in userType.GetMethods()) 24 { 25 Console.WriteLine(method.Name); 26 } 27 } 28 29 MethodInfo showMethod = userType.GetMethod("Show"); // 4. 获取指定方法 30 var result = showMethod.Invoke(instance, null); // 5. 方法调用 31 Console.WriteLine(result); 32 33 Console.ReadLine(); 34 } 35 } 36 }
相关文章: