检索 Func 中执行的调用方法的名称
我想获取作为 Func 委托的方法的名称。
Func<MyObject, object> func = x => x.DoSomeMethod();
string name = ExtractMethodName(func); // should equal "DoSomeMethod"
我怎样才能实现这个目标?
-- 为了吹牛的权利 --
让 ExtractMethodName
也可以使用属性调用,让它返回该实例中的属性名称。
例如。
Func<MyObject, object> func = x => x.Property;
string name = ExtractMethodName(func); // should equal "Property"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
瞧,妈! 没有表情树!
这是一个快速、肮脏且特定于实现的版本,它从底层 lambda 的 IL 流中获取元数据令牌并解析它。
Look Ma! No expression trees!
Here's a quick, dirty and implementation-specific version that grabs the metadata token from the IL stream of the underlying lambda and resolves it.
我认为在一般情况下这是不可能的。 如果你有:
你会期望什么?
话虽这么说,您可以使用反射来打开 Func 对象并查看它的内部功能,但您只能在某些情况下解决它。
I don't think this is possible in the general case. What if you had:
What would you expect?
That being said, you could use reflection to open up the Func object and see what it does inside, but you'll only be able to solve it for certain cases.
在这里查看我的黑客答案:
为什么会有不是 C# 中的“fieldof”或“methodof”运算符?
过去我用另一种方式使用
Func
而不是Expression> ;
,但我对结果不太满意。 当使用属性时,用于检测fieldof
方法中字段的MemberExpression
将返回PropertyInfo
。编辑#1:这适用于问题的一部分:
编辑#2:无论是谁标记我,都应该花一点时间来了解这里发生了什么。 表达式树可以与 lambda 表达式一起隐式使用,并且是获取此处特定请求信息的最快、最可靠的方法。
Check out my hack answer here:
Why is there not a `fieldof` or `methodof` operator in C#?
In the past I did it another way that used
Func
instead ofExpression<Func<...>>
, but I was much less pleased with the result. TheMemberExpression
used to detect the field in myfieldof
method will return aPropertyInfo
when a property is used.Edit #1: This works for a subset of the problem:
Edit #2: Whoever marked me down should take a second to realize what's going on here. The expression trees can be implicitly used with lambda expressions and are the fastest, most reliable way to get the specific requested information here.