For parameters, use expression. parameter to create the parameterexpression object. Note that the parameter can be valid only when the parameterexpression array is input during Lambda creation.
For local variables, the expression type provides the variable method, but the variable method returns the parameterexpression. In fact, they create the same parameterexpression object. The only difference is that the parameter method considers the type. isbyref, but variable throws an exception (if type. isbyref is true ). Note that local variables must be passed in the parameterexpression array when blockexpression is created.
For the returned value, you must first create a labeltarget object through partial overload of expression. label, and then return gotoexpression through the return method of expression (indirectly calling makegoto). Note that it is associated with a labeltarget object. Finally, use another part of expression. label to return the labelexpression overload to create a label expression, that is, the labelCodeBlock. Finally, the labeltarget object can be marked by type or by type together with name.
The following code creates a Lambda statement similar to the following method:
Static StringDoo (IntI)
{
StringStr=I.Tostring ();
ReturnSTR;
}
All code:
// + Using system. reflection;
// + Using system. LINQ. expressions;
// Parameters
VaRPa= Expression.Parameter (Typeof(Int),"I");
// Local variable
VaRLoc= Expression.Variable (Typeof(String),"Str");
// Create labeltarget to return values
LabeltargetLabeltarget= Expression.Label (Typeof(String));
// Call I. tostring ()
MethodcallexpressionMed= Expression.Call (Pa,Typeof(Object).Getmethod ("Tostring",New Type[] {});
// Assign the result to the local string variable
BinaryexpressionAsn= Expression.Assign (LOC, Med );
// Create a return expression (actually a goto expression)
GotoexpressionRET= Expression.Return (labeltarget, Loc );
// Create a target label for the returned expression
LabelexpressionLBL= Expression.Label (labeltarget,Expression.Constant (String.Empty ));
// Generate blockexpression
BlockexpressionBlocks= Expression.Block (
New Parameterexpression[] {Loc },
Asn,
RET,
LBL );
// Generate a Lambda expression
Expression func int , string >> Lam = Expression . Lambda func int , string >> (blocks,
New Parameterexpression[] {Pa });
// Run and output the result
Func<Int,String>Del=Lam.Compile ();
Console.Writeline (DEL (17));
Output:
17