我正在努力思考如何为更多的 lambda 构建表达式树,例如下面的表达式,更不用说可能有多个语句的东西了。例如:
Func<double?, byte[]> GetBytes
= x => x.HasValue ? BitConverter.GetBytes(x.Value) : new byte[1] { 0xFF };
如果有任何想法,我将不胜感激。
最佳答案
我建议通读 list of methods on the Expression class ,您的所有选项都列在那里,Expression Trees Programming Guide .
对于这个特定的实例:
/* 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();
关于c# - 构建表达式树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6273788/