суббота, 9 февраля 2013 г.

Invoking Generic Methods Using Reflection


This is by no means any detailed post on how to use reflection. The other day I had the need to use reflection to call a generic method. So after playing around with reflection for few minutes I figured it out.  Here is how the code looks like.

namespace ConsoleApplication7
{
    class Printing
    {
        public void PrintAnyThing(T print)
        {
            Console.WriteLine(print);
        }
    }
 
class Program
{
    static void Main(string[] args)
    {
        Type type = typeof(Printing);
        Object instance = Activator.CreateInstance(type);
        MethodInfo genericmethod = type.GetMethod("PrintAnyThing");
        MethodInfo closedmethod = genericmethod.MakeGenericMethod(typeof(string));
        closedmethod.Invoke(instance, new object[]{"Zeeshan"});
 
    }
}
}
Here is how the generic method looks like.
image
Here is how you would invoke it.
image
The generic method is pretty simple. I am taking a parameter of type T which makes it a generic method. I simply print that generic parameter value to the console as the method name states.
In the order to call the generic method, I first create an instance of Printing class by calling Activator.CreateInstance passing in type of object I want to instantiate. The reason I am creating an instance of Printing type is because PrintAnyThing generic method is an instance method. If the method would have been static I do not need to create an instance of it. Next from the type, I try to get method info for PrintAnyThing. Notice at this point it is still a generic method and I cannot invoke it directly. I need to convert it to closed method by specifying the value for T which I do by making a call to MakeGenericMethod. Once I have the closed method, I pass in the instance on which this method is to be invoked along with the method arguments that the method requires.

Комментариев нет: