I want to list all methods of a type with a specific method signature.
For example, if a type has a few public methods:
public void meth1 (int i);
public void meth2 (int i, string s);
public void meth3 (int i, string s);
public int meth4 (int i, string s);
I want to list all the methods which expect an int as first and a string as second parameter and returns void.
How can I do this?
You can use something like this:
public static class Extensions
{
public static IEnumerable<MethodInfo> GetMethodsBySig(this Type type, Type returnType, params Type[] parameterTypes)
{
return type.GetMethods().Where((m) =>
{
if (m.ReturnType != returnType) return false;
var parameters = m.GetParameters();
if ((parameterTypes == null || parameterTypes.Length == 0))
return parameters.Length == 0;
if (parameters.Length != parameterTypes.Length)
return false;
for (int i = 0; i < parameterTypes.Length; i++)
{
if (parameters[i].ParameterType != parameterTypes[i])
return false;
}
return true;
});
}
}
And use it like this:
var methods = this.GetType().GetMethodsBySig(typeof(void), typeof(int), typeof(string));
This is the extension method to use improved from EvgK's answer.
private static IEnumerable<MethodInfo> GetMethodsBySig(this Type type,
Type returnType,
Type customAttributeType,
bool matchParameterInheritence,
params Type[] parameterTypes)
{
return type.GetMethods().Where((m) =>
{
if (m.ReturnType != returnType) return false;
if ((customAttributeType != null) && (m.GetCustomAttributes(customAttributeType, true).Any() == false))
return false;
var parameters = m.GetParameters();
if ((parameterTypes == null || parameterTypes.Length == 0))
return parameters.Length == 0;
if (parameters.Length != parameterTypes.Length)
return false;
for (int i = 0; i < parameterTypes.Length; i++)
{
if (((parameters[i].ParameterType == parameterTypes[i]) ||
(matchParameterInheritence && parameterTypes[i].IsAssignableFrom(parameters[i].ParameterType))) == false)
return false;
}
return true;
});
}
Use it like
var methods = SomeTypeToScan.GetMethodsBySig(
typeof(SomeReturnType),
typeof(SomeSpecialAttributeMarkerType),
true,
typeof(SomeParameterType))
.ToList();
type.GetMethods().Where(p =>
p.GetParameters().Select(q => q.ParameterType).SequenceEqual(new Type[] { typeof(int), typeof(string) }) &&
p.ReturnType == typeof(void)
);
You'll have to inspect all MethodInfo
s yourself. By calling MethodInfo.GetParameters()
you'll get a collection of ParameterInfo
objects, which in turn have a property ParameterType
.
The same for the return type: inspect the ReturnType
property of MethodInfo
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With