How can I create a C #. Net generic class instance through the reflection mechanism in C #. NET and call its method ??
Reward score: 40 | resolution time: | Questioner: rjgaoyuan
Here is a simple and easy-to-understand example... Common Reflection classes and generic reflection classes are different... Public abstract class businessmanager {// <summary> /// Add a new object // </Summary> /// <Param name = "entity"> </param> public Virtual void add <t> (T mappedinstance) where T: entity {type entitymanage = typeof (entitymanager <t>); object OBJ = activator. createinstance (entitymanage); methodinfo method = entitymanage. getmethod ("add"); method. invoke (OBJ, new object [] {mappedinstance}) ;}} is similar to this, but this is a reflection of common classes. Method, there is an error here. I hope to help me change it to reflect the generic class and change it. Entitymanager <t> is a generic class.
Best Answer
The difference between generic reflection and normal reflection is the processing of generic parameters. Let's take a look at a simple example. Class class1 <t> {public void test (t) {console. writeline (t) ;}} to use reflection to dynamically create an instance of this type and call the test method, we can use the following method. Type type = typeof (class1 <int>); object o = activator. createinstance (type); type. invokemember ("test", bindingflags. default | bindingflags. invokemethod, null, O, new object [] {123}); but if the generic parameters are not fixed, what should we do? In fact, type has added a similar processing mechanism. Static void invoketest (type T, Params object [] ARGs) {type = typeof (class1 <>); type = type. makegenerictype (t); object o = activator. createinstance (type); type. invokemember ("test", bindingflags. default | bindingflags. invokemethod, null, O, argS);} another situation is the generic method. Let's continue. The class class1 {public void test <t> (t) {console. writeline (t) ;}} method is similar, except that methodinfo. makegenericmethod () is used this time (). Static void invoketest (type T, Params object [] ARGs) {type = typeof (class1); object o = activator. createinstance (type); methodinfo method = type. getmethod ("test", bindingflags. instance | bindingflags. public); method = method. makegenericmethod (t); method. invoke (O, argS );}