简体   繁体   中英

Getting the MethodInfo of static method of a static class

I'm trying to get the MethodInfo of a static method in a static class. When running the following line, I only get the basic 4 methods, ToString, Equals, GetHashCode and GetType:

MethodInfo[] methodInfos = typeof(Program).GetMethods();

How can I get the other methods that are implemented in this class?

var methods = typeof(Program).GetMethods(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

试试这种方式:

MethodInfo[] methodInfos = typeof(Program).GetMethods(BindingFlags.Static | BindingFlags.Public);

Also if you know your static method and have access to it at a compile time, you could use Expression class to get MethodInfo without directly using reflection (which may cause additional runtime errors):

public static void Main()
{
    MethodInfo staticMethodInfo = GetMethodInfo( () => SampleStaticMethod(0, null) );

    Console.WriteLine(staticMethodInfo.ToString());
}

//Method that is used to get MethodInfo from an expression with a static method call
public static MethodInfo GetMethodInfo(Expression<Action> expression)
{
    var member = expression.Body as MethodCallExpression;

    if (member != null)
        return member.Method;

    throw new ArgumentException("Expression is not a method", "expression");
}

public static string SampleStaticMethod(int a, string b)
{
    return a.ToString() + b.ToLower();
}

Here actual parameters passed to a SampleStaticMethod does not matter as only body of SampleStaticMethod is used, so you could pass null and default values to it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM