Uri*_*rik 12 c# visual-studio-2010
我正在尝试在静态类中获取静态方法的MethodInfo.运行以下行时,我只获得基本的4种方法,ToString,Equals,GetHashCode和GetType:
MethodInfo[] methodInfos = typeof(Program).GetMethods();
Run Code Online (Sandbox Code Playgroud)
如何获得此类中实现的其他方法?
var methods = typeof(Program).GetMethods(BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
Run Code Online (Sandbox Code Playgroud)
试试这种方式:
MethodInfo[] methodInfos = typeof(Program).GetMethods(BindingFlags.Static | BindingFlags.Public);
Run Code Online (Sandbox Code Playgroud)
此外,如果您知道您的静态方法并且可以在编译时访问它,您可以使用Expressionclass 来获取MethodInfo而不直接使用反射(这可能会导致额外的运行时错误):
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();
}
Run Code Online (Sandbox Code Playgroud)
这里传递给 a 的实际参数SampleStaticMethod无关紧要,因为只使用了 body SampleStaticMethod,因此您可以将null默认值传递给它。
| 归档时间: |
|
| 查看次数: |
6949 次 |
| 最近记录: |