仅从Type.GetMethods()中获取具有特定签名的方法 [英] Get only Methods with specific signature out of Type.GetMethods()
本文介绍了仅从Type.GetMethods()中获取具有特定签名的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想列出具有特定方法签名的类型的所有方法。
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);
我想列出所有期望将int作为第一个参数并将字符串作为第二个参数并返回的方法
I want to list all the methods which expect an int as first and a string as second parameter and returns void.
我该怎么办?
推荐答案
您可以使用类似这样的东西:
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;
});
}
}
并像这样使用它:
var methods = this.GetType().GetMethodsBySig(typeof(void), typeof(int), typeof(string));
这篇关于仅从Type.GetMethods()中获取具有特定签名的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文