开发者

Examining a lambda expression at runtime in C#

开发者 https://www.devze.com 2022-12-30 19:32 出处:网络
I have a method Get on a type MyType1 accepting a Func<MyType2, bool> as a parameter. An example of its use:

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 exa开发者_高级运维mines 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?


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.


public void Get<T>(Expression<Func<T,bool>> expr)
{
  // look at expr
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号