从表达式树中提取方法名称?
我正在尝试实现以下模式函数:
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 .对象,系统.Reflection.Met hodInfo)
I am trying to implement the following pattern function:
MethodInfo GetMethod(
Expression<Func<TTarget, EventHandler<TEventArgs>>> method)
I can provide an instance of TTarget if required
The desired usage is:
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你已经成功一半了。
看下面的代码
并使用下面的代码来获取方法名称。
我希望这能回答你的问题。
You're half way there.
Look at the code below
And use the following code to get the method name.
I hope this answers your question.