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

前端之家收集整理的这篇文章主要介绍了c# – 从表达式树中提取方法名称?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试实现以下模式函数
MethodInfo GetMethod(      
  Expression<Func<TTarget,EventHandler<TEventArgs>>> method)

如果需要,我可以提供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)
{
}

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

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

打印出来:

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

解决方法

你在那里的一半.
看下面的代码
public static void Main(string[] args)
{
    var program = new Program();
    var methodInfo = GetMethod<Program,EventArgs>(()=> program.Method);
    Console.WriteLine(methodInfo.Name);
}

并使用以下代码获取方法名称.

static MethodInfo GetMethod<TTarget,TEventArgs>(Expression<Func<EventHandler<TEventArgs>>> method) where TEventArgs:EventArgs
{
    var convert = method.Body as UnaryExpression;
    var methodCall = (convert.Operand as MethodCallExpression);
    if (methodCall != null && methodCall.Arguments.Count>2 && methodCall.Arguments[2] is ConstantExpression)
    {
        var methodInfo = (methodCall.Arguments[2]as ConstantExpression).Value as MethodInfo;
        return methodInfo;
    }
    return null;
}

我希望这回答了你的问题.

原文链接:https://www.f2er.com/csharp/100195.html

猜你在找的C#相关文章