Building Expression Trees

I struggle with the idea of ​​creating an expression tree for more lambda, for example, below, not to mention that it can have several statements. For instance:

Func<double?, byte[]> GetBytes = x => x.HasValue ? BitConverter.GetBytes(x.Value) : new byte[1] { 0xFF }; 

I would be grateful for any thoughts.

+6
source share
1 answer

I would suggest reading a list of methods of the Expression class , all of your parameters are listed here, and the Expression Tree Programming Guide .

Regarding this specific example:

 /* build our parameters */ var pX = Expression.Parameter(typeof(double?)); /* build the body */ var body = Expression.Condition( /* condition */ Expression.Property(pX, "HasValue"), /* if-true */ Expression.Call(typeof(BitConverter), "GetBytes", null, /* no generic type arguments */ Expression.Member(pX, "Value")), /* if-false */ Expression.Constant(new byte[] { 0xFF }) ); /* build the method */ var lambda = Expression.Lambda<Func<double?,byte[]>>(body, pX); Func<double?,byte[]> compiled = lambda.Compile(); 
+5
source

Source: https://habr.com/ru/post/890012/


All Articles