We can call methods defined by a type using reflection.To call the method defined by a type using reflection we use the MethodInfo class.MethodInfo is defined in the System.Reflection namespace.
To invoke a method defined by a type using reflection we need to implement the following
1. Obtain Type object for the type defining the method.
In this example we will be using the following class
class ReflectionTest { public void Hello(string message) { Console.WriteLine("Hello {0}",message); } public void Hello() { Console.WriteLine("Hello"); } }
To obtain the Type reference use the typeof operator and pass the name of type for which we need to obtain the Type reference
Type obj = typeof(ReflectionTest);
2. Call GetMethods() on the type object obtained by calling typeof() operator.GetMethods() returns an array of type MethodInfo.
MethodInfo[] miColl = typeof(ReflectionTest).GetMethods();
Above will return list of all methods defined by the ReflectionTest class.
static void Main(string[] args) { ReflectionTest rt = new ReflectionTest(); Type obj = typeof(ReflectionTest); MethodInfo[] miColl = typeof(ReflectionTest).GetMethods(); foreach (MethodInfo mi in miColl) { Console.WriteLine(mi.Name); } Console.ReadLine(); }
Executing the above will print all the methods defined by the ReflectionTest class including the methods defined by the base Object class:
Hello
Hello
ToString
Equals
GetHashCode
GetType
To obtain a method with a specific name pass the name of the method as a parameter to the GetMethod().This will return MethodInfo object for the specified method.
But we have defined overloaded Hello method ,so if we just pass the name of the method to the GetMethod() then we will get System.Reflection.AmbiguousMatchException
exception.
MethodInfo mi=typeof(ReflectionTest).GetMethod("Hello");
So we need call another overload GetMethod(string,type[]) .This method returns a methodinfo object based on the parameters types.These parameter types
are passed in the Type array as the second argument.
MethodInfo mi=typeof(ReflectionTest).GetMethod("Hello",new Type[]{typeof(string)});
3. Call Invoke on the MethodInfo instance which we got in step 2.To the Invoke() method we need to pass the parameters and the object which we created in step 1.
Parameters correspond to the parameters defined for the method.Here we are passing the string “reflection”.
static void Main(string[] args) { ReflectionTest rt = new ReflectionTest(); Type obj = typeof(ReflectionTest); MethodInfo mi=typeof(ReflectionTest).GetMethod("Hello",new Type[]{typeof(string)}); mi.Invoke(rt, new object[] {"reflection"}); Console.ReadLine(); }
On executing the above code we get the following
So as we have seen for calling overloaded methods using Reflection we use GetMethod method.We use an overload of GetMethod which accepts Type array corresponding to method parameters.
Leave a Reply