开发者

Traverse Expression, find MethodCallExpression and replace with new Expression

I have an expression like this Expression<Func<IInterface, object>>

How do i loop/traverse through all expressions inside the expression and find any MethodCallExpression that uses the input parameter of the Func (IInterface), to call a method like this

inputParameter => inputParameter.MyMethod(typeof(SomeClass))

or an Generic Extension method like this

inputParameter => inputParameter.MyMethod<SomeClass>()

If one of the two methods are found, i need get the Type passed. For the Generic Extension method it would be the Generic parameter which is the Type, in the other method call it is the first argument supplied for the parameters in the method call

The signature of the 2 methods look like this

object MyMethod(Type type)
T MyMethod<T>(this IInterface param) where T : class

The type from one of the two Method Calls is then used to lookup another Expression<Func<IInterface, object>> and replace the method call with the "content" of the expression.

Anyone who can help me with how this can be done ?

Short

Search an Expression for any call to one of two methods, if found, get the type used in the call, and lookup the expression registered for the type (i got it in a dictionary) and replace the method call with what the expression is doing.

Example

Here is an example of what i am trying to accomplish. If i have the following two Expression<Func<IInterface, object>> declared for type Bar1 and Bar开发者_StackOverflow中文版2

Bar1: x => new Foo1(x.MyMethod(typeof(Bar2)))
Bar2: x => new Foo2()

Solving/Combining them the Func<IInterface, object> for Bar1 will be changed to end up looking like this

Bar1: x => new Foo1(new Foo2())

The x.MyMethod(typeof(Bar2)) call in the Lambda registered for type Bar1 is replaced with the new Foo2() call registered for type Bar2.

Need more information?

Please let me know if you need more information to understand my question.


You're looking for the ExpressionVisitor class.

You can inherit this class and override VisitMethodCall to check whether it's calling a method you're interested in, and, if so, return a new Expression that does something else to replace the method call.

This class is new to .Net 4.0.
In .Net 3.5, you can copy the class from here.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜