Four reflection methods

Source: Internet
Author: User

Four reflection methods

Reflection is. net provides a technology for accessing the content of a class or class. It allows you to access a class when you have no idea about a class at compilation, you can use a string to discover, access, or call a class. The following describes four reflection methods using an instance:

First, a class is designed to simulate the called class.

public class TestClass     {        private string testType;        public string TestType        {            get { return testType; }            set { testType = value; }        }        private string testType2;        public string TestType2        {            get { return testType2; }            set { testType2 = value; }        }        public TestClass()        {            testType2 = "test";        }        public int test1()        {            int i = 1;            i++;            return i;        }        public void testsomething()        {            int i = 0;        }    }
The above code is only for testing. It is generally estimated that no one will write such code, so do not despise it. To simulate reflection calls, I encapsulate this class in a class named testlibrary. dll class library.

Then, first list the code of the four methods, and then pay attention to the explanation.

        delegate void delegatetest(Type t);        private const BindingFlags flags = BindingFlags.DeclaredOnly | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance;
// Method 1 private void TestInvoke1 (Type t) {object obj = t. invokeMember (null, flags | BindingFlags. createInstance, null); Console. writeLine (obj. getType (). toString (); string testresult = t. invokeMember ("testType2", flags | BindingFlags. getField, null, obj, null ). toString (); Console. writeLine (testresult); t. invokeMember ("testType2", flags | BindingFlags. setField, null, obj, new object [] {"grass mud horse"}); testresult = t. invokeMember ("testType2", flags | BindingFlags. getField, null, obj, null ). toString (); Console. writeLine (testresult); testresult = t. invokeMember ("test1", BindingFlags. invokeMethod, null, obj, null ). toString (); Console. writeLine (testresult );}
// Method 2 private void TestInvoke2 (Type t) {ConstructorInfo ctor = t. getConstructor (new Type [] {}); object obj = ctor. invoke (new object [] {}); FieldInfo fi = t. getField ("testType", flags); fi. setValue (obj, "Nima"); Console. writeLine (fi. getValue (obj); MethodInfo mi = t. getMethod ("test1", flags); string result = mi. invoke (obj, null ). toString (); Console. writeLine (result );}
// Method 3 delegate int testdelegate (); private void TestInvoke3 (Type t) {object obj = Activator. createInstance (t); MethodInfo mi = t. getMethod ("test1", flags); var test1 = (testdelegate) (mi. createDelegate (typeof (testdelegate), obj); int I = test1 (); Console. writeLine (I. toString (); PropertyInfo pi = t. getProperty ("TestType", flags); var SetTestType = (Action
 
  
) Delegate. CreateDelegate (typeof (Action
  
   
), Obj, pi. GetSetMethod (); try {SetTestType ("Nima");} catch {Console. WriteLine ("cannot be written! ");} Var GetTestType = (Func
   
    
) Delegate. CreateDelegate (typeof (Func
    
     
), Obj, pi. GetGetMethod (); Console. WriteLine ("Get Result:" + GetTestType ());}
    
   
  
 
// Method 4 private void TestInvoke4 (Type t) {dynamic obj = Activator. createInstance (t); try {obj. testType = ""; Console. writeLine (obj. testType. toString ();} catch {Console. writeLine ("private fields cannot be read or written");} try {obj. testType = "2"; Console. writeLine (obj. testType);} catch {Console. writeLine ("Private attributes cannot be read or written");} try {Func
 
  
Test = () => obj. test1 (); Console. WriteLine (test ();} catch {Console. WriteLine ("Private methods cannot be read or written ");}}
 
First, observe that all the parameters passed in the four methods have a type parameter. This parameter obtains the type of the class to be accessed by reflection, first, we will introduce how to access classes of this type.

First, method 1 uses the most direct method, but reflection is a performance-consuming call method. method 1 binds each method or attribute called, the performance consumption is relatively high and the speed is relatively slow. First, the Type InvokeMember method is used to call the t-Type constructor to construct an instance, however, because we do not know what type it is during running, we can only assign it to an object. The first parameter of InvokeMember represents the name of the content to be accessed, such as the name of an attribute or method. Because it is an access constructor, we pass in a null value. The second parameter controls the binding execution flag. It specifies the types to be bound and is separated by the | symbol. For example, in the example, the defined DeclaredOnly specifies that reflection does not consider the inheritance type, nonPublic specifies the reflection of Non-public members. Therefore, reflection can be used to access private members without special processing of data. The fourth parameter is the bound instance, when calling a constructor, you can pass in a null value. To call a property or field or method, you must pass in the object instance returned by the constructor. The last parameter is the parameter to be passed in, which is of the object [] type. After understanding this, you can basically use the InvokeMember method to call various types in an unknown class. The instance provides examples of calling fields and methods, the accessed testType2 is a private field, but it can still be accessed.


Then, method 2, and method 2 provide a way to bind an attribute and call multiple times. When multiple instances need to call the same method repeatedly, this method provides better performance, because all operations are bound only once. This time, the GetConstructor method of the Type is called using another method to call the constructor method, this method searches for the matched constructor in the Assembly based on the parameter type specified by the input parameter and returns a ConstructorInfo instance. This instance provides access to the constructor, in method 2 above, we passed in an empty Type [] array, so the instance returned by this method will provide access to the non-argument constructor, then, call the invoke method of this instance and input parameters to obtain the instance type, which is also an object. Then, we use the GetField and GetMethod methods of the Type to obtain access to specific fields and methods, and then we can access the corresponding methods and fields. Similarly, you can use the GetProperty method to obtain access to the property.


Method 3 provides a way to use the delegated access type. This method is suitable for repeatedly calling the same members in the same instance, when the same member in the same object is called multiple times, the performance of this method is superior to that provided by method 2. It is still constructing an instance, and then getting access to members. But this time it is constructing a delegate and directing the delegate to this member, but this method does not provide access to fields, for attribute access, you can construct a get accessor set accessor to direct the delegate to the attribute to access the attribute.


Method 4 provides a method to use dynamic to access the class. Before we constructed the instance, we all returned an object, but this time we assigned the returned value to a dynamic, this type will be parsed at runtime and will not be parsed during compilation. Calling in this way is easy to understand and intuitive, and it also provides good performance, however, the disadvantage is that, because the parsing is not performed during compilation, vs's powerful smart prompt function cannot be used, and no errors will be reported during compilation, you may use a lot of try catch, mainly because you may access non-existent or private members in this way. At this time, errors will be captured, this is also required.

Let's briefly explain the four methods. Next we will explain how to discover class members and obtain the class type.

Assembly a = Assembly.LoadFrom("testlibrary.dll");            foreach (Type t in a.GetExportedTypes())            {                if (t.Name.ToString() == "TestClass")                {                    Console.WriteLine(t.FullName);                    object o = Activator.CreateInstance(t);                    Console.WriteLine(o.GetType());                    foreach (MemberInfo info in t.GetMembers(BindingFlags.DeclaredOnly | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance))                    {                        Console.WriteLine(info);                    }                    TestInvoke1(t);                 }                }
The above Code provides methods to discover class members using Assembly. the LoadFrom method loads the previously generated assembly. The GetExportedTypes method gets all the public types, and you can obtain the member types in this class through the obtained types, at this time, we only need the type of the class, and then pass in the corresponding method. For details about the process, refer to the sample code. The code is relatively simple, so it won't be too long.


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.