Reflection on Generics

Source: Internet
Author: User
Today, when I was using reflection, I suddenly thought that I had never reflected generic objects before, so I decided to try it.
First, obtain the type of a generic class and enter the following code:
  1. Type T = type. GetType ("system. Collections. Generic. List <int> ");

However, debugging found that t is null. It seems that the class name is incorrect. Try again, system. collections. generic. list or error. Try system again. collections. generic. list <t>, or not. I tried several times in succession, or not, Mao. First, let's see what type of list <int> is. type the following code to view it:

  1. List <int> List = new list <int> ();
  2. Type T = List. GetType ();
  3. Console. writeline (T. fullname );

Result output: system. Collections. Generic. List '1 [[system. int32, mscorlib, version = 2.0.0.0, culture = neutral, publickeytoken = b77a5c561934e089]
I'm dizzy. Why is that? Try again.

  1. Type T = type. GetType ("system. Collections. Generic. List '1 [system. int32]");

Debug again. Okay. This is the right time.
Next, let's call the add method of list <int> and insert a data record to it.

  1. Methodinfo add = T. getmethod ("add", new type [1] {typeof (INT)}); // locate the Add Method
  2. Object List = T. invokemember (null,
  3. Bindingflags. declaredonly |
  4. Bindingflags. Public | bindingflags. nonpublic |
  5. Bindingflags. instance | bindingflags. createinstance, null, null, new object [] {}); // instantiate a list <int> Object List
  6. Add. Invoke (list, new object [] {12356}); // call the add method to insert a data entry to the list.
  7. Type T2 = List. GetType ();
  8. Console. writeline (t2.invokemember ("item", bindingflags. getproperty, null, list, new object [] {0}); // obtain the first index output of the List

The output result is correct. Next I want to use reflection to call the generic method and write the following code:

  1. Methodinfo convert = t2.getmethod ("convertall", bindingflags. Public | bindingflags. instance); // obtain the convertall generic Method
  2. Object list2 = type. GetType ("system. Collections. Generic. List '1 [system. String]"). invokemember (null, bindingflags. declaredonly |
  3. Bindingflags. Public | bindingflags. nonpublic |
  4. Bindingflags. instance | bindingflags. createinstance, null, null, new object [] {}); // instantiate a list <string> Object list2 to store converted data.
  5. List2 = convert. Invoke (list, new object [] {New converter <int, string> (convert. tostring)}); // call the convertall Method
  6. Console. writeline (list2.gettype (). invokemember ("item", bindingflags. getproperty, null, list, new object [] {0}); // output the first index value of list2

Debugging again, but unfortunately, the following error occurs: you cannot bind the containsgenericparameters type or method.
What's going on? After reading the following msdn, The methodinfo. containsgenericparameters attribute is interpreted:

To call a generic method, the type parameters of the method or any closed type must not include the generic type definition or open construction type. It is very difficult to perform such recursive validation. For convenience and to reduce errors, containsgenericparameters
Attribute provides a standard method to distinguish between a closed Constructor (which can be called) and an open Constructor (which cannot be called ). If the containsgenericparameters attribute returns true, the method cannot be called.

This seems to be because I did not pass the generic type first. I checked msdn again and found the makegenericmethod method. This method

Replace the type parameter defined by the current generic method with the element of the type array, and return the methodinfo object that represents the result constructor. You can try again. Add the following code before invoke:

  1. Convert = convert. makegenericmethod (typeof (string ));

Debug again, OK, normal. Now, we have successfully called the generic reflection. complete code:

  1. Type T = type. GetType ("system. Collections. Generic. List '1 [system. int32]");
  2. Methodinfo add = T. getmethod ("add", new type [1] {typeof (INT )});
  3. Object List = T. invokemember (null,
  4. Bindingflags. declaredonly |
  5. Bindingflags. Public | bindingflags. nonpublic |
  6. Bindingflags. instance | bindingflags. createinstance, null, null, new object [] {});
  7. Add. Invoke (list, new object [] {12356 });
  8. Type T2 = List. GetType ();
  9. Console. writeline (t2.invokemember ("item", bindingflags. getproperty, null, list, new object [] {0 }));
  10. Methodinfo convert = t2.getmethod ("convertall", bindingflags. Public | bindingflags. instance );
  11. Object list2 = type. GetType ("system. Collections. Generic. List '1 [system. String]"). invokemember (null, bindingflags. declaredonly |
  12. Bindingflags. Public | bindingflags. nonpublic |
  13. Bindingflags. instance | bindingflags. createinstance, null, null, new object [] {});
  14. Convert = convert. makegenericmethod (typeof (string ));
  15. List2 = convert. Invoke (list, new object [] {New converter <int, string> (convert. tostring )});
  16. Console. writeline (list2.gettype (). invokemember ("item", bindingflags. getproperty, null, list2, new object [] {0 }));

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.