在 C# 中运行时检查 lambda 表达式
我在类型 MyType1
上有一个方法 Get
,接受 Func
作为参数。
其使用示例:
mytype1Instance.Get(x => x.Guid == guid));
我想创建方法 Get
的存根实现,该方法检查传入的 lambda 表达式并确定 guid
的值。显然,lambda 可以是“任何东西”,但我很高兴存根对 lambda 做出假设,即它试图在 Guid
属性上进行匹配。
我该怎么做?我怀疑它涉及到内置 Expression
类型的使用?
I have a method Get
on a type MyType1
accepting a Func<MyType2, bool>
as a parameter.
An example of its use:
mytype1Instance.Get(x => x.Guid == guid));
I would like create a stub implementation of the method Get
that examines the incoming lambda expression and determines what the value of guid
is. Clearly the lambda could be "anything", but I'm happy for the stub to make an assumption about the lambda, that it is trying to match on the Guid
property.
How can I do this? I suspect it involves the use of the built-in Expression
type?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
看一下 Typed Reflector,它是一个简单的单源文件组件,提供从强类型成员访问到相应的 MemberInfo 实例的桥梁。
即使您可能无法使用它,它也应该让您很好地了解可以使用表达式做什么。
Take a look at Typed Reflector, which is a simple single-source-file component that provides a bridge from strongly typed member access to corresponding MemberInfo instances.
Even if you may not be able to use it as, it should give you a good idea about what you can do with Expressions.