我想列出具有特定方法签名的所有类型的方法.
例如,如果类型有一些公共方法:
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);
Run Code Online (Sandbox Code Playgroud)
我想列出所有期望int为first的方法,将字符串作为第二个参数,并返回void.
我怎样才能做到这一点?
Evg*_*vgK 13
你可以使用这样的东西:
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;
});
}
}
Run Code Online (Sandbox Code Playgroud)
并像这样使用它:
var methods = this.GetType().GetMethodsBySig(typeof(void), typeof(int), typeof(string));
Run Code Online (Sandbox Code Playgroud)
type.GetMethods().Where(p =>
p.GetParameters().Select(q => q.ParameterType).SequenceEqual(new Type[] { typeof(int), typeof(string) }) &&
p.ReturnType == typeof(void)
);
Run Code Online (Sandbox Code Playgroud)
您必须MethodInfo亲自检查所有内容。通过调用,MethodInfo.GetParameters()您将获得对象的集合ParameterInfo,这些对象又具有属性ParameterType。
返回类型也是如此:检查ReturnType的属性MethodInfo。
| 归档时间: |
|
| 查看次数: |
6575 次 |
| 最近记录: |