Reflection basis, light reflection

Source: Internet
Author: User

Reflection basis, light reflection

 

Reflection is a process used to obtain information in a class or discover and run an assembly while the program is running. Through reflection, the information in the set with the extension of "cmd.dll" and" cmd.exe "can be obtained. Using Reflection, You can see information about classes, interfaces, fields, attributes, methods, and features in an assembly.

First define a class

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace ConsoleApplication2{    [Serializable]    class Poster    {                    private int count;                   public string OwnerName { get; set; }                   public string Title { get; set; }                       public string Content { get; set; }            public void makePoster(string titile,string content) {                Title = titile;                Content = content;            }            public string getPoster() {                               return  "Title: "+Title+" Content: " +Content +" postby"+OwnerName;            }            public string getPoster(string s) {                return s;            }            }}
 

 

1. Get the Type object
    • Use a string such:
       Type t1 = Type.GetType("ConsoleApplication2.Poster"); 
    • Specific classes:
      Type t2 = typeof(ConsoleApplication2.Poster);
    • Instance:
       Poster p = new Poster(); Type t3 = p.GetType(); 
2. Use the System. Reflection. Assembly class
 
 
  • You can use Assembly to dynamically Load an Assembly and view its internal information. The most common method is Load.
    Assembly assembly = Assembly.Load("MyAssembly");  

    Note that there are three methods to Load the Assembly in Assembly: Load, LoadFrom, and LoadFile. What are the similarities and differences between the three methods?

    1. if you reference a namespace, you can directly Load it by using the Load () method. Enter the namespace + class name in the parameter.

    2. If you only know a dll file, you must use the LoadFrom () method. Enter the complete path in the parameter.

    The LoadFrom method has the following Disadvantages. Consider using Load instead.

    -If an assembly with the same identifier has been loaded, LoadFrom returns the loaded Assembly even if different paths are specified.
    -If you use LoadFrom to load an assembly and then load an assembly in the context to try to load an assembly with the same display name, the loading attempt will fail. This may occur when deserializing an assembly.

    Conclusion: LoadFrom can only be used to load an assembly with different identifiers, that is, a unique assembly. It cannot be used to load an assembly with the same identifiers but different paths.

    3. LoadFile: loads the content of the Assembly file in the specified path .)

    This method is to Load the Assembly from the specified file. It is the method of calling the external API to Load the assembly, the difference between the LoadFrom method is that this method does not load other Assembly referenced by this Assembly, that is, it does not load program dependencies. At the same time, the Assembly with the same identifier cannot be loaded.

    The object CreateInstance (string) method of Assembly can be used to create an object. parameter 0 is the class name.

3. System. Reflection common classes
 
 
Type Function
Assembly This class can be used to load and manipulate an assembly and obtain internal information of the Assembly.
EventInfo This class stores the specified event information
FieldInfo This class stores the given field information
MethodInfo This class saves the given method information
MemberInfo This class is a base class that defines multiple public behaviors of EventInfo, FieldInfo, MethodInfo, and PropertyInfo.
Module This class allows you to access the given modules in multiple assemblies.
ParameterInfo This class saves the given parameter information
PropertyInfo This class saves the given property information
4. Reflection Method

See MethodInfo in the 3 Summary table list. Pay attention to whether to reload the method when calling the method. The following Code indicates that the method is obtained with the same method name and different signatures, generally, if there is only one method, you only need to use

GetMethod ("method name ")

Private static void rec () {Poster pp = new Poster (); Type p = Type. getType ("leleapplication2.poster"); Console. writeLine (p. toString (); Type p2 = typeof (leleapplication2.poster); Console. writeLine (p2.ToString (); Console. writeLine (pp. getType (). toString (); string path = AppDomain. currentDomain. setupInformation. applicationBase + "leleapplication2.exe"; Assembly ss = Assembly. loadFrom (path); Console. writeLine (ss. getType ("leleapplication2.poster "). toString () + "4"); Module mod = ss. getModules () [0]; Console. writeLine (mod. getType ("leleapplication2.poster "). toString () + "5"); // The above is the loading method MethodInfo [] methodList = p. getMethods (); foreach (MethodInfo info in methodList) {Console. writeLine (info. toString (); // method list} object object_p = Activator. createInstance (p); // instantiate an object Type [] types = new Type [1]; types [0] = typeof (string); MethodInfo meth = p. getMethod ("getPoster", types); // obtain the getPoser (string s) method object [] ob = new object [1]; // input parameter ob [0] = "good dog"; Console. writeLine (meth. invoke (object_p, ob); // call this method Type [] types2 = new Type [0]; MethodInfo meth2 = p. getMethod ("getPoster", types2); // obtain the getPoster () method Console. writeLine (meth2.Invoke (object_p, null ));}

The result is as follows:

 

The property generation method is displayed here. The list of methods obtained by reflection is public by default.

5. Reflection attributes

The reflection property is obtained using the PropertyInfo in the list, which is basically the same as the method writing format. One GetProperties is for enumeration, and the other is GetProperty for example. Values and values are assigned through SetValue and GetValue.

Private static void rec2 () {Type p = Type. getType ("leleapplication2.poster"); // obtain the Console of the reflection object. writeLine (p. toString (); PropertyInfo [] p_info = p. getProperties (); // get all public attributes of reflection foreach (PropertyInfo p_in p_info) {Console. writeLine (p_in.ToString ();} object p_r = Activator. createInstance (p); // create an instance PropertyInfo ptile = p. getProperty ("Title"); // obtain the Title property ptile. setValue (p_r, "this is the topic"); // set the property value Console. writeLine (ptile. getValue (p_r ). toString (); // obtain the attribute value}
The output result is
6. Comprehensive use cases of attributes and Methods

For property replication, the value can be processed through methods

Private static void ATest () {Type poster = typeof (leleapplication2.poster); object newposter = Activator. createInstance (poster); PropertyInfo p_owner = poster. getProperty ("OwnerName"); p_owner.SetValue (newposter, "Keith"); // assign MethodInfo p_make = poster to the user. getMethod ("makePoster"); // obtain the makePoster method object [] para = new object [2]; para [0] = "Weather "; para [1] = "the weather in Beijing has been really bad recently"; p_make.Invoke (newposter, para); // input the parameter Type [] types = new Type [0]; methodInfo p_getposter = poster. getMethod ("getPoster", types); // get the getPoster method. Note that it is different from the makePoster Console. writeLine (p_getposter.Invoke (newposter, null); // output}

Output result

Private static void setPosterRec () {Dictionary <string, string> oneposter = new Dictionary <string, string> (); oneposter. add ("OwnerName", "Keith"); oneposter. add ("Title", "Reply to Rita"); oneposter. add ("Content", "The weather is really not good"); Type poster = typeof (leleapplication2.poster); object newposter = Activator. createInstance (poster); PropertyInfo [] pinfo = poster. getProperties (); foreach (PropertyInfo p in pinfo) {if (oneposter. containsKey (p. name) {p. setValue (newposter, Convert. changeType (oneposter [p. name], p. propertyType);} Poster thisp = newposter as Poster; Console. writeLine (thisp. getPoster ());}
7. Batch assignment of simulated attribute values

 

Private static void setPosterRec () {Dictionary <string, string> oneposter = new Dictionary <string, string> (); oneposter. add ("OwnerName", "Keith"); oneposter. add ("Title", "Reply to Rita"); oneposter. add ("Content", "The weather is really bad"); // assume that the data comes from xml Type poster = typeof (leleapplication2.poster); object newposter = Activator. createInstance (poster); PropertyInfo [] pinfo = poster. getProperties (); // get the attribute list foreach (PropertyInfo p in pinfo) {if (oneposter. containsKey (p. name) {// The enumerated property list is assigned a value of p based on the same attribute Name and dictionary key value. setValue (newposter, Convert. changeType (oneposter [p. name], p. propertyType); // Convert. changeType (oneposter [p. name], p. propertyType), assign values according to the reflected object type} Poster thisp = newposter as Poster; Console. writeLine (thisp. getPoster ());}

The key to this code is Convert. changeType (oneposter [p. name], p. propertyType) Here, the value in the dictionary is converted to the same type in the Poster class. Otherwise, an error is reported during the value assignment.

Output result

8. Read fields and features in the class

Poster has a private field Count. Let's change the output. The output of the feature is GetCustomAttribute.

Private static void getprivateRec () {Type poster = typeof (leleapplication2.poster); object newposter = Activator. createInstance (poster);/* FieldInfo reads fields in the class. The first is the field name, followed by the enumerated parameter values, including private and public */FieldInfo file = poster. getField ("count", BindingFlags. nonPublic | BindingFlags. instance | BindingFlags. public);/* with the same attributes */file. setValue (newposter, 200); Console. writeLine (file. getValue (newposter);/* output feature */object [] typeAttribute = poster. getCustomAttributes (false); foreach (object a in typeAttribute) {Console. writeLine (. toString ());}}

Output result

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.