获取静态类的静态方法的MethodInfo

时间:2012-06-28 14:52:18

标签: c# visual-studio-2010

我正在尝试在静态类中获取静态方法的MethodInfo。运行以下行时,我只获得基本的4种方法,ToString,Equals,GetHashCode和GetType:

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

如何获得此类中实现的其他方法?

3 个答案:

答案 0 :(得分:9)

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

答案 1 :(得分:5)

尝试这种方式:

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

答案 2 :(得分:3)

此外,如果您知道静态方法并且在编译时可以访问它,则可以使用Expression类来获取MethodInfo而无需直接使用反射(这可能会导致其他运行时错误):< / p>

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

此处传递给SampleStaticMethod的实际参数无关紧要,因为只使用SampleStaticMethod的正文,因此您可以将null和默认值传递给它。