Mega Code Archive

 
Categories / C# / Reflection
 

Generic methods, like nongeneric methods, can be invoked dynamically at run time

using System; using System.Reflection; public class GenericZ<K, V, Z>     where K : new()     where V : new() {     public void MethodA<A>(A argument1, Z argument2) {         Console.WriteLine("MethodA invoked");     }     private K field1 = new K();     private V field2 = new V(); } class Starter {     static void Main() {         Type genericType = typeof(GenericZ<,,>);         Type[] parameters ={typeof(int),typeof(float),                 typeof(int)};         Type closedType = genericType.MakeGenericType(parameters);         MethodInfo openMethod = closedType.GetMethod("MethodA");         object newObject = Activator.CreateInstance(closedType);         parameters = new Type[] { typeof(int) };         MethodInfo closedMethod =             openMethod.MakeGenericMethod(parameters);         object[] methodargs = { 2, 10 };         closedMethod.Invoke(newObject, methodargs);     } }