Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
256 views
in Technique[技术] by (71.8m points)

c# - Get only Methods with specific signature out of 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);

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...