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 programmatically.
If I have the name of a method (a string), the type that declares it (an instance of System.Type), and a list of argument types I want to be able to call a standard library function and get back a MethodInfo object representing the method the C# compiler would choose to invoke.
For instance if I have
class MyClass {
public void myFunc(BaseClass bc) {};
public void myFunc(DerivedClass dc) {};
}
Then I want something like this fictional function GetOverloadedMethod on System.Type
MethodInfo methodToInvoke
= typeof(MyClass).GetOverloadedMethod("myFunc", new System.Type[] {typeof(BaseClass)});
In this case methodToInvoke should be public void myFunc(BaseClass bc).
NOTE: Neither of the methods GetMethod and GetMethods will serve my purpose. Neither of them do any overload resolution. In the case of GetMethod it only returns exact matches. If you give it more derived arguments it will simply return nothing. Or you might be lucky enough to get an ambiguity exception which provides no useful information.
Answer
Use
Type.GetMethod(String name, Type[] types)to do programmatic overload resolution. Here is an example:Explanation
In the example,
methodToInvokewill bemyFunc(BaseClass bc)notmyFunc(DerivedClass dc), because thetypesarray specifies the parameter list of the method to get.From the MSDN documentation,
Type.GetMethod(String name, Type[] types)has two parameters:nameis the name of the method to get, andtypesprovides the order, number, and types of the method's parameters.Running Code
Here is a running fiddle that demonstrates programmatic overload resolution.
The output is
BaseClass.Edit: This is robust.
GetMethodresolved methods that takeparams, more derived classes, delegates, and interface implementations. This Fiddle demonstrates all of those cases. Here are the calls and what they retrieve.Works with
paramswill resolve this method
Works with more derived classes
resolves a method that takes the
MoreDerivedClassWorks with delegates
... will retrieve a method that takes this delegate:
Works with interface implementations
... successfully retrieves a method that takes
MyImplementationSo, it is robust, and we can use
GetMethodto do overload resolution in cases that we might not expect to work.