13.07.2015 Views

C# in Depth

C# in Depth

C# in Depth

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Expression trees243the tree and how parameters are bound. We start off by work<strong>in</strong>g out everyth<strong>in</strong>g weneed to know about the method call that forms the body of the f<strong>in</strong>al expression B:the target of the method (<strong>in</strong> other words, the str<strong>in</strong>g we’re call<strong>in</strong>g StartsWith on); themethod itself (as a MethodInfo); and the list of arguments (<strong>in</strong> this case, just the one).It so happens that our method target and argument will both be parameters passed<strong>in</strong>to the expression, but they could be other types of expressions—constants, theresults of other method calls, property evaluations, and so forth.After build<strong>in</strong>g the method call as an expression C, we then need to convert it<strong>in</strong>to a lambda expression D, b<strong>in</strong>d<strong>in</strong>g the parameters as we go. We reuse the sameParameterExpression values we created as <strong>in</strong>formation for the method call: theorder <strong>in</strong> which they’re specified when creat<strong>in</strong>g the lambda expression is the order <strong>in</strong>which they’ll be picked up when we eventually call the delegate.Figure 9.3 shows the same f<strong>in</strong>al expression tree graphically. To be picky, eventhough it’s still called an expression tree, the fact that we reuse the parameter expressions(and we have to—creat<strong>in</strong>g a new one with the same name and attempt<strong>in</strong>g tob<strong>in</strong>d parameters that way causes an exception at execution time) means that it’s not atree anymore.lambdaExpressionNodeType=LambdaType=System.BooleanBodyParameterscallMethodCallExpressionNodeType=CallType=System.BooleanlambdaParametersCollection ofParameterExpressionsMethodArgumentsObject(Conta<strong>in</strong>s)methodmethodArgstargetMethodInfo forstr<strong>in</strong>g.StartsWith(str<strong>in</strong>g)(Conta<strong>in</strong>s)Collection ofExpressionsParameterExpressionNodeType=ParameterType=System.Str<strong>in</strong>gName="x"methodArgParameterExpressionNodeType=ParameterType=System.Str<strong>in</strong>gName="y"(Conta<strong>in</strong>s)Figure 9.3 Graphical representation of expression tree that calls a method and uses parameters froma lambda expressionLicensed to Rhona Hadida

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!