C# 检查表达式树中的值是否为null的最佳方法

C# 检查表达式树中的值是否为null的最佳方法,c#,expression-trees,C#,Expression Trees,检查表达式树中的常量是否为null的最佳方法是什么 // 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_na

检查表达式树中的常量是否为null的最佳方法是什么

// 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));
//要调用的方法(Regex.IsMatch)
MethodInfo isMatchMethod=typeof(Regex).GetMethod(“IsMatch”,新[]{typeof(string)、typeof(string)、typeof(RegexOptions)});
//要计算的成员:(x=>x)
var member=Expression.Property(param,propertyName);
//要计算的值
var常量=Expression.Convert(Expression.constant(value),type);
//如何检查常量是否为空???
var expr=Expression.Call(isMatchMethod,member,constant,Expression.constant(RegexOptions.IgnoreCase));
//不起作用
//表达式notNullConstant=值!=无效的常量:Expression.Convert(Expression.constant(string.Empty),type);
//var expr=Expression.Call(isMatchMethod,member,notNullConstant,Expression.Constant(RegexOptions.IgnoreCase));

不确定问题出在哪里。你可以翻译
a??b
表达式按字面意思合并成一棵树。合并
。如果有疑问,请使用C#编译器编译一个表达式,并查看它的功能


同时,您询问了如何编译
?:
。答案是一样的:只需对现有代码进行反编译即可查看输出的内容。使用
Expression.Condition

不使用
Expression.Constant(值、类型)
的任何原因?它不是那种类型的常数吗?你能告诉我们更多的背景吗?你看过这个答案吗?“不行”是什么意思?还有,你到底想做什么?实际上,您没有在表达式树中测试null,因此您的问题有点令人困惑。我想使用表达式树得到类似的结果:Regex.IsMatch(property,pattern??string.Empty,RegexOptions.IgnoreCase)嗯,三元运算符
expression.Condition
。尽管如此,我还是建议使用
Expression.Coalesce
。是的,但在我的例子中?:Expression是更好的变体。怎么写?