C#反射 发表于 2021-10-03 | 分类于 C# 字数统计: 266 | 阅读时长 ≈ 1 反射就是操作C#代码编译后的dll文件,可以获取程序集中的所有数据,并调用运行时类的方法。 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354static void Main(string[] args){ // 方式一:通过加载dll文件获取指定Type Assembly assembly = Assembly.LoadFrom("Library.dll"); Type type = assembly.GetType("Libaray.Student"); // 获取所有Type var types = assembly.GetTypes(); foreach (Type t in types) { Console.WriteLine(t.Name); } // 方式二:通过typeof() 获取Type Type type1 = typeof(Libaray.Student); // 调用无参构造 object student = Activator.CreateInstance(type); Console.WriteLine(student); // 调用有参构造 object student1 = Activator.CreateInstance(type, new object[] { "2017001", "zhangyuzhen", 22 }); Console.WriteLine(student1); // 调用私有构造 object student2 = Activator.CreateInstance(type, true); Console.WriteLine(student2); // 调用方法 var method = type.GetMethod("Print", BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic); method.Invoke(student2,new object[] { "zyz",22}); // 调用泛型方法 var method1 = type.GetMethod("Func", BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic); var genericMethod = method1.MakeGenericMethod(new Type[] { typeof(int) }); genericMethod.Invoke(student2, new object[] {}); // 获取所有属性并设置值 var properties = type.GetProperties(); foreach(var property in properties){ if (property.Name == "Id") { property.SetValue(student, "001"); }else if (property.Name == "Name") { property.SetValue(student, "zhangsan"); } else { property.SetValue(student, 18); } } Console.WriteLine(student);} 本文作者: Zhangyuzhen 本文链接: https://sweetboyzhang.github.io/2021/10/03/csharp-03/ 版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 3.0 许可协议。转载请注明出处!