When the C# compiler interprets a method invocation it must use (static) argument types to determine which overload is actually being invoked. I want to be able to do this prog
Use Type.GetMethod(String name, Type[] types)
to do programmatic overload resolution. Here is an example:
MethodInfo methodToInvoke = typeof(MyClass)
.GetMethod("myFunc", new System.Type[] { typeof(BaseClass) });
In the example, methodToInvoke
will be myFunc(BaseClass bc)
not myFunc(DerivedClass dc)
, because the types
array specifies the parameter list of the method to get.
From the MSDN documentation, Type.GetMethod(String name, Type[] types)
has two parameters:
name
is the name of the method to get, andtypes
provides the order, number, and types of the method's parameters.Here is a running fiddle that demonstrates programmatic overload resolution.
using System;
using System.Reflection;
public static class Program
{
public static void Main()
{
MethodInfo methodToInvoke = typeof(MyClass)
.GetMethod("myFunc", new System.Type[] { typeof(BaseClass) });
var result = methodToInvoke
.Invoke(new MyClass(), new object[] { new BaseClass() });
Console.WriteLine(result);
}
public class MyClass
{
public static string myFunc(BaseClass bc) {
return "BaseClass";
}
public static string myFunc(DerivedClass dc) {
return "DerivedClass";
}
}
public class BaseClass { }
public class DerivedClass : BaseClass { }
}
The output is BaseClass
.
GetMethod
resolved methods that take params
, more derived classes, delegates, and interface implementations. This Fiddle demonstrates all of those cases. Here are the calls and what they retrieve.
params
MethodInfo methodToInvoke2 = typeof(MyClass).GetMethod(
"myFunc",
new System.Type[] { typeof(Int32[]) });
will resolve this method
public static string myFunc(params int[] i)
{
return "params";
}
MethodInfo methodToInvoke3 = typeof(MyClass).GetMethod(
"myFunc",
new System.Type[] { typeof(MoreDerivedClass) });
resolves a method that takes the MoreDerivedClass
public class BaseClass { }
public class DerivedClass : BaseClass { }
public class MoreDerivedClass : DerivedClass {}
MethodInfo methodToInvoke4 = typeof(MyClass).GetMethod(
"myFunc",
new System.Type[] { typeof(MyDelegate) });
... will retrieve a method that takes this delegate:
public delegate void MyDelegate(string x);
MethodInfo methodToInvoke5 = typeof(MyClass).GetMethod(
"myFunc",
new System.Type[] { typeof(MyImplementation) });
... successfully retrieves a method that takes MyImplementation
public interface IMyInterface {}
public class MyImplementation : IMyInterface {}
So, it is robust, and we can use GetMethod
to do overload resolution in cases that we might not expect to work.