Method Matching
-
Hello everyone, I am trying to find all methods that have a particular signature. In other words, I want all methods that match the return type and parameter types of a specified method. I have a solution, but I was wondering if a more elegant approach exists. Using delegates is one possibility, but delegates are not very “edit-and-continue” friendly. Here is my current solution:
void findSimilarMethods()
{
MethodInfo example = this.GetType().GetMethod("ExampleMethod");
ParameterInfo[] parameters = example.GetParameters();
List matches = new List();MethodInfo\[\] methods = this.GetType().GetMethods(); foreach (MethodInfo current in methods) { ParameterInfo\[\] currentParams = current.GetParameters(); if ( current.ReturnType != example.ReturnType ) continue; if ( currentParams.Length != parameters.Length ) continue; if ( !ParameterEquality(parameters, currentParams) ) continue; matches.Add(current); }
}
// a helper method to check parameter type equality
bool ParameterEquality(ParameterInfo[] a, ParameterInfo[] b)
{
if (a.Length != b.Length)
return false;
for (int i = 0; i < a.Length; i++)
if (a[i].GetType() != b[i].GetType())
return false;
return true;
}Any suggestions would be greatly appreciated. -Steve
-
Hello everyone, I am trying to find all methods that have a particular signature. In other words, I want all methods that match the return type and parameter types of a specified method. I have a solution, but I was wondering if a more elegant approach exists. Using delegates is one possibility, but delegates are not very “edit-and-continue” friendly. Here is my current solution:
void findSimilarMethods()
{
MethodInfo example = this.GetType().GetMethod("ExampleMethod");
ParameterInfo[] parameters = example.GetParameters();
List matches = new List();MethodInfo\[\] methods = this.GetType().GetMethods(); foreach (MethodInfo current in methods) { ParameterInfo\[\] currentParams = current.GetParameters(); if ( current.ReturnType != example.ReturnType ) continue; if ( currentParams.Length != parameters.Length ) continue; if ( !ParameterEquality(parameters, currentParams) ) continue; matches.Add(current); }
}
// a helper method to check parameter type equality
bool ParameterEquality(ParameterInfo[] a, ParameterInfo[] b)
{
if (a.Length != b.Length)
return false;
for (int i = 0; i < a.Length; i++)
if (a[i].GetType() != b[i].GetType())
return false;
return true;
}Any suggestions would be greatly appreciated. -Steve
Why not use one of the other overloads of
GetMethod
MSDN[^], like the one that takes the method name and aType []
for the parameters? And you don't really need to match return type if you're matching parameter types, because you can't overload methods based on return type alone.Regards Senthil [MVP - Visual C#] _____________________________ My Blog | My Articles | My Flickr | WinMacro