当前位置: 首页 > 科技观察

如何在C#中使用反射

时间:2023-03-15 14:52:34 科技观察

本文转载请联系码农阅读公众号。C#中的反射常用于在程序运行时获取类型元数据。可以获得的信息包括已经加载到进程中的程序集和类型信息。它类似于C++中的RTTI(运行时类型信息)。.为了能够使用反射,您需要在项目中引用System.Reflection命名空间。在开始使用反射的时候,你会得到一个Type类型的对象,并进一步从这个对象中得到程序集、类型、模块等信息,可以动态地反射生成某个类型的实例,甚至可以动态调用上的方法这个类型。在System.Reflection命名空间下,定义了以下核心类型。AssemblyModuleEnumMethodInfoConstructorInfoMemberInfoParameterInfoTypeFieldInfoEventInfoPropertyInfo现在让我们一起研究如何使用它,考虑下面定义的Customer类。publicclassCustomer{publicintId{get;set;}publicstringFirstName{get;set;}publicstringLastName{get;set;}publicstringAddress{get;set;}}下面的代码片段展示了如何通过反射命名空间。classProgram{staticvoidMain(string[]args){Typetype=typeof(Customer);Console.WriteLine("Class:"+type.Name);Console.WriteLine("Namespace:"+type.Namespace);}}看看再比如,如何通过反射获取Customer下的所有属性,并在控制台显示所有属性名,如下代码所示:staticvoidMain(string[]args){Typetype=typeof(Customer);PropertyInfo[]属性信息=类型。GetProperties();Console.WriteLine("ThelistofpropertiesoftheCustomerclassare:--");foreach(PropertyInfopInfoinpropertyInfo){Console.WriteLine(pInfo.Name);}}值得注意的是typeof(Customer).GetProperties()只能通过default是一个公共属性集,对应Customer类下的四个公共属性。接下来我们看一下如何通过反射获取类型下的构造函数和public方法的元数据信息。这里我们继续使用Customer类,并为该类添加构造函数和Validate方法。该方法用于验证输入参数。合法性,下面是修改后的Customer类。publicclassCustomer{publicintId{get;set;}publicstringFirstName{get;set;}publicstringLastName{get;set;}publicstringAddress{get;set;}publicCustomer(){}publicboolValidate(CustomercustomerObj){//Codetovalidatethecustomerobjectreturntrue;}}然后看通过反射获取到Customer下所有定义的构造函数,但是这里只定义了一个构造函数,所以只能列出一个。classProgram{staticvoidMain(string[]args){Typetype=typeof(Customer);ConstructorInfo[]constructorInfo=type.GetConstructors();Console.WriteLine("TheCustomerclasscontainsthefollowingConstructors:--");foreach(ConstructorInfocinconstructorInfo){Consolec.WriteLine);}}}另请注意,默认情况下GetConstructors()方法只能获取标记为公共的Customer的所有构造函数。接下来看看如何显示Customer中所有的公共方法,因为这个类中只定义了一个公共方法,所以控制台应该只显示一个,以下代码仅供参考。staticvoidMain(string[]args){Typetype=typeof(Customer);MethodInfo[]methodInfo=type.GetMethods();Console.WriteLine("ThemethodoftheCustomerclassare:--");foreach(MethodInfotempinmethodInfo){Console.WriteLine(temp.Name);}Console.Read();}是不是很奇怪,刚才说只有一个方法,但是还有好几个方法,要知道多的方法来自两个方面。从对象类型继承的公共方法。编译器自动生成的属性方法。如果方法标有Attribute,也可以通过GetCustomAttributes方法获取。参考代码如下:staticvoidMain(string[]args){foreach(MethodInfotempinmethodInfo){foreach(Attributeattributeintemp.GetCustomAttributes(true)){//Writeyourusualcodehere}}}相信在你的应用中,你会经常使用各种Attributeson域实体。这时候就可以使用上面的代码反射来提取领域实体上的方法。属性信息,以便根据提取的属性执行您特定的业务逻辑。翻译链接:https://www.infoworld.com/article/3027240/how-to-work-with-reflection-in-c.html