This article describes the implementation method of C# creating custom generics through reflection in an example form, and shares it with you for your reference. The details are as follows:
For example, there is a generic type like this: <T,TT> I want to create an instance of <string,int> through reflection, which can be created in the following format:
().CreateInstance("Namespace.User`form parameter quantity N[[1 full name of the formal parameter type, assembly name where the formal parameter type is located],[2 full name of the formal parameter type, assembly name where the formal parameter type is located],[3 full name of the formal parameter type, assembly name where the formal parameter type is located]...N]")
The example code is as follows:
namespace Demo { public class GenericsSimple<T,TT> where T:class where TT:struct {} class Program { static void Main(string[] args) { var o = ().CreateInstance("`2[[, mscorlib],[System.Int32, mscorlib]]"); ("{0}",o==null?"null":().FullName); ("===end==="); (); } } }
I hope this example will be helpful to everyone's C# programming.