C # basic reflection knowledge and practical application

Source: Internet
Author: User
Tags custom name

C # basic reflection knowledge and practical application
First, what is reflection? Reflection provides an object that encapsulates the Assembly, module, and Type (Type). You can use reflection to dynamically create an instance of the Type, bind the Type to an existing object, or obtain the Type from an existing object, then, you can call methods of the type or access its fields and attributes. In short, with reflection, many previously unfeasible functions can be implemented. The following is a small example to show how reflection works: Open VS2010 and create a console application in program. the code written in cs first introduces the namespace: using System. reflection; the following code: PropertyInfo len = typeof (string ). getProperty ("Length"); string s = "Hello, reflection! "; Int length = (int) len. getValue (s, null); Console. writeLine (length. toString (); here, the Length attribute of the string is obtained through reflection, and the property value is obtained by calling the GetValues method of PropertyInfo. The prototype of the GetValues method is as follows: public virtual object GetValue (object obj, object [] index); the first parameter obj is an instance of the class with this attribute. In this example, the string s and s have the Length attribute. The second parameter is the index value. Microsoft interprets it as follows: Optional index values for indexed properties. this value shoshould be null for non-indexed properties. generally, null is used. You can study it in depth. The GetValues method returns the object type, so the conversion type must be mandatory. The following is a method to obtain the string through reflection. The Code is as follows: string s = "Hello, reflection! "; MethodInfo method = typeof (string ). getMethod ("Contains"); bool result = (bool) method. invoke (s, new object [] {"Hello"}); Console. writeLine (result); The Invoke method is defined as follows: public object Invoke (object obj, object [] parameters); this is a good understanding, the first parameter is the instance of the class that owns this method, or the string instance s. the second parameter is the parameter of an object array. Here, the Contains method in string is called to determine whether the string Contains a certain string. The following code instantiates a string object through reflection: Type t = Type. getType ("System. string "); char [] para = new char [] {'h', 'E', 'l', 'l', 'O'}; var o = Activator. createInstance (t, para); Console. writeLine (o); this is similar to the get method. The only difference is that the string constructor parameter is a char [] array, so it must be of the correct type. Here, a string is instantiated and the value is Hello. Now that you have a preliminary understanding of reflection, you can start to use the solution: Right-click the solution, add a project, select a class library, enter a name, and add a class library. Add the Custom class to the class library. The Code is as follows: copy the code using System; using System. collections. generic; using System. linq; using System. text; namespace ReflectionDll {public class Custom {public string Name {get; set;} public string Address {get; set;} public int Age {get; set ;} public DateTime BirthDay {get; set;} public string GetInfo (string name = "", int age = 0) {if (name = "" & age = 0) {return "Custom Name:" + t His. name + ", Age:" + this. age ;}else {return "Custom Name:" + name + ", Age:" + age ;}}} copy the code. Here, only several attributes and a method are declared, for demonstration. Compile the library and add the reference class library in the console project (for convenience, otherwise, you must manually copy the DLL to the console project for each compilation ), in this way, VS will automatically copy the generated DLL to the debug directory on the console for convenient calling. Run the following code to load the DLL using reflection: string path = Environment. currentDirectory + "\ ReflectionDll. dll "; Assembly assem = Assembly. loadFile (path); Type customType = assem. getType ("ReflectionDll. custom "); var custom = Activator. createInstance (customType); note that you need to obtain the physical path of the DLL first, so it doesn't matter whether to add the reference above. After the path is available, load the DLL using the LoadFile method of Assembly and obtain the Type of the class. Note that the parameters in the GetType method must be the full name of the class and namespace + class name, otherwise, it cannot be found. In the last row, an instance of the class is created and the type is object. The following code gets all the attributes of M: copy the code PropertyInfo [] propertys = customType. getProperties (); Console. writeLine ("******************************"); foreach (PropertyInfo pro in propertys) {Console. writeLine ("PropertyName:" + pro. name + "\ n" + "PropertyType:" + pro. propertyType + "\ n" + "ClassName:" + pro. reflectedType + "\ n" + "DLLName:" + pro. module + "\ n");} Console. writeLine ("**************************** ** "); Copy the code to obtain all attributes by calling the GetProperties method, save it to the PropertyInfo [] array, and traverse the output attribute values of the array. The following describes the meaning of each attribute: Name attribute Name PropertyType attribute Name control of the class where the data type ReflectedType is located + DLL file Name where the class Name Module is located to set the value of a property. The method is as follows: propertyInfo p = customType. getProperty ("Name"); p. setValue (custom, "CustomName", null); isn't it easy... The following describes how to call the class method and some attributes. The Code is as follows: copy the code MethodInfo _ method = customType. getMethod ("GetInfo"); // display the method name Console. writeLine ("Invoke method:" + _ method. name); // display the returned data type Console. writeLine ("Return type:" + _ method. returnParameter); ParameterInfo [] parameters = _ method. getParameters (); foreach (ParameterInfo pa in parameters) {Console. writeLine (pa. name + pa. parameterType + pa. position + pa. member);} object [] paras = new object [] {"Jack", 24}; Console. writeLine (_ method. invoke (custom, paras); the copy code is the same as the property. The parameter can be obtained through GetParameters (). The obtained parameter information is as follows: name parameter Name ParameterType parameter data type Position parameter location Member output all parameters when calling a method with parameters, You need to input a parameter, a New object array, write the parameters in order.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.