【发布时间】:2017-04-28 15:10:10
【问题描述】:
请参阅下面的示例代码。如何修改它以处理空值,类似于?. 运算符的工作方式?
class Program
{
static LambdaExpression GetExpression(Expression<Func<string, string>> expr)
{
return expr;
}
static void Main(string[] args)
{
// I want to perform the following null propagation check
// in the expression tree below.
// (s as string)?.Replace("a", "o");
var expr = GetExpression(t => t);
var oldValue = Expression.Constant("a", typeof(string));
var newValue = Expression.Constant("o", typeof(string));
var mi = typeof(string).GetMethod(nameof(string.Replace), new[] { typeof(string), typeof(string) });
var invoke = Expression.Invoke(expr, expr.Parameters);
var call = Expression.Call(invoke, mi, oldValue, newValue);
var lambda = Expression.Lambda(call, false, expr.Parameters);
Console.WriteLine(lambda.Compile().DynamicInvoke("gaga"));
// Should print empty line. Not throw!
Console.WriteLine(lambda.Compile().DynamicInvoke(null));
}
}
【问题讨论】:
标签: c# lambda expression-trees