在表达式树中检查常量是否为空的最佳方法是什么?
// Method to call (Regex.IsMatch)
MethodInfo isMatchMethod = typeof(Regex).GetMethod("IsMatch", new[] { typeof(string), typeof(string), typeof(RegexOptions) });
// The member you want to evaluate: (x => x.<property_name>)
var member = Expression.Property(param, propertyName);
// The value you want to evaluate
var constant = Expression.Convert(Expression.Constant(value), type);
// How to check if constant is null???
var expr = Expression.Call(isMatchMethod, member, constant, Expression.Constant(RegexOptions.IgnoreCase));
// Doesn't work
// Expression notNullConstant = value != null ? constant : Expression.Convert(Expression.Constant(string.Empty), type);
//var expr = Expression.Call(isMatchMethod, member, notNullConstant, Expression.Constant(RegexOptions.IgnoreCase));
答案 0 :(得分:3)
不确定问题是什么。您可以将Button
字面翻译成a ?? b
的树。如果有疑问,请使用C#编译器编译表达式并查看它的作用。
与此同时,您已经询问如何编译Expression.Coalesce
。答案是一样的:只需反编译现有代码即可查看输出内容。使用?:
。