c# - How do I use reflection to call a generic method? -


what's best way call generic method when type parameter isn't known @ compile time, instead obtained dynamically @ runtime?

consider following sample code - inside example() method, what's concise way invoke genericmethod<t>() using type stored in mytype variable?

public class sample {     public void example(string typename)     {         type mytype = findtype(typename);          // goes here call genericmethod<t>()?         genericmethod<mytype>(); // doesn't work          // changes call staticmethod<t>()?         sample.staticmethod<mytype>(); // doesn't work     }      public void genericmethod<t>()     {         // ...     }      public static void staticmethod<t>()     {         //...     } } 

you need use reflection method start with, "construct" supplying type arguments makegenericmethod:

methodinfo method = typeof(sample).getmethod("genericmethod"); methodinfo generic = method.makegenericmethod(mytype); generic.invoke(this, null); 

for static method, pass null first argument invoke. that's nothing generic methods - it's normal reflection.

as noted, lot of simpler of c# 4 using dynamic - if can use type inference, of course. doesn't in cases type inference isn't available, such exact example in question.


Popular posts from this blog

php - How should I create my API for mobile applications (Needs Authentication) -

5 Reasons to Blog Anonymously (and 5 Reasons Not To)

Google AdWords and AdSense - A Dynamic Small Business Marketing Duo