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

C# 获取静态类的静态方法的MethodInfo,c#,visual-studio-2010,C#,Visual Studio 2010,我试图在静态类中获取静态方法的MethodInfo。在运行以下代码行时,我只获得了基本的4个方法:ToString、Equals、GetHashCode和GetType: MethodInfo[] methodInfos = typeof(Program).GetMethods(); 如何获取该类中实现的其他方法?请尝试以下方法: var methods = typeof(Program).GetMethods(BindingFlags.Static | BindingFlags.Instan

我试图在静态类中获取静态方法的MethodInfo。在运行以下代码行时,我只获得了基本的4个方法:ToString、Equals、GetHashCode和GetType:

MethodInfo[] methodInfos = typeof(Program).GetMethods();
如何获取该类中实现的其他方法?

请尝试以下方法:

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

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

publicstaticvoidmain()
{
MethodInfo staticMethodInfo=GetMethodInfo(()=>SampleStaticMethod(0,null));
Console.WriteLine(staticMethodInfo.ToString());
}
//方法,该方法用于通过静态方法调用从表达式获取MethodInfo
公共静态MethodInfo GetMethodInfo(表达式)
{
var member=expression.Body作为MethodCallExpression;
如果(成员!=null)
返回成员。方法;
抛出新ArgumentException(“表达式不是方法”、“表达式”);
}
公共静态字符串SampleStaticMethod(int a,string b)
{
返回a.ToString()+b.ToLower();
}

这里,传递给
SampleStaticMethod
的实际参数并不重要,因为只使用了
SampleStaticMethod
的主体,所以您可以将
null
和默认值传递给它。

在这种情况下,我得到了0个方法。。。我是从同一个类还是从主方法运行它有关系吗?更新。。。获取所有方法,包括静态和实例、公共和非公共
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();
}