相关疑难解决方法(0)

从表达式树中提取方法名称?

我正在尝试实现以下模式函数:

MethodInfo GetMethod(      
  Expression<Func<TTarget, EventHandler<TEventArgs>>> method)
Run Code Online (Sandbox Code Playgroud)

如果需要,我可以提供TTarget的实例

所需的用法是:

public static void Main(string[] args)
{
    var methodInfo = GetMethod<Program, EventArgs>(t => t.Method);
    Console.WriteLine("Hello, world!");
}

private void Method(object sender, EventArgs e)
{
}
Run Code Online (Sandbox Code Playgroud)

这是我到目前为止所尝试的:

private static MethodInfo GetMethod(TTarget target, Expression<Func<TTarget, EventHandler<TEventArgs>>> method)
{
  var lambda = method as LambdaExpression;
  var body = lambda.Body as UnaryExpression;
  var call = body.Operand as MethodCallExpression;
  var mInfo = call.Method as MethodInfo;

  Console.WriteLine(mInfo);

  throw new NotImplementedException();
}
Run Code Online (Sandbox Code Playgroud)

打印出来:

System.Delegate CreateDelegate(System.Type, System.Object, System.Reflection.Met hodInfo)

.net c# linq reflection expression-trees

7
推荐指数
1
解决办法
2127
查看次数

标签 统计

.net ×1

c# ×1

expression-trees ×1

linq ×1

reflection ×1