提取前pression树法的名字吗? [英] Extract method name from expression tree?
本文介绍了提取前pression树法的名字吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想实现以下模式功能:
I am trying to implement the following pattern function:
MethodInfo GetMethod(
Expression<Func<TTarget, EventHandler<TEventArgs>>> method)
如果需要,我可以提供TTarget的实例
I can provide an instance of TTarget if required
所需的用法是:
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)
{
}
下面是我到目前为止已经试过:
Here's what I've tried so far:
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();
}
它打印出来:
It prints out:
System.Delegate CreateDelegate(System.Type的,System.Object的,System.Reflection.Met
hodInfo)
System.Delegate CreateDelegate(System.Type, System.Object, System.Reflection.Met
hodInfo)
推荐答案
你成功了一半。 看看下面
You're half way there. Look at the code below
public static void Main(string[] args)
{
var program = new Program();
var methodInfo = GetMethod<Program, EventArgs>(()=> program.Method);
Console.WriteLine(methodInfo.Name);
}
和使用下面的code,以获得方法名。
And use the following code to get the method 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;
}
我希望这回答了你的问题。
I hope this answers your question.
这篇关于提取前pression树法的名字吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文