fork download
  1. using System;
  2. using System.Linq;
  3.  
  4. public class Test
  5. {
  6. public static void Main()
  7. {
  8. new Test().Run();
  9. }
  10.  
  11. public void Run()
  12. {
  13. //type you need to create generic version with
  14. var type = GetType().Assembly //assumes it is located in current assembly
  15. .GetTypes()
  16. .Single(t => t.Name == "MyType");
  17.  
  18. //creating a closed generic method
  19. var method = GetType().GetMethod("Query")
  20. .GetGenericMethodDefinition()
  21. .MakeGenericMethod(type);
  22.  
  23. //calling it on this object
  24. method.Invoke(this, null); //will print "Called Query with type: MyType"
  25. }
  26.  
  27. public void Query<T>()
  28. {
  29. Console.WriteLine("Called Query with type: {0}", typeof(T).Name);
  30. }
  31. }
  32. public class MyType { }
Success #stdin #stdout 0.04s 24232KB
stdin
Standard input is empty
stdout
Called Query with type: MyType