Get only Methods with specific signature out of Type.GetMethods()

后端 未结 5 1423
梦毁少年i
梦毁少年i 2020-12-03 18:23

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);
pu         


        
5条回答
  •  悲&欢浪女
    2020-12-03 19:06

    You can use something like this:

    public static class Extensions
    {
        public static IEnumerable 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));
    

提交回复
热议问题