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

时间:2015-07-10 08:47:39

标签: c# expression-trees

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

// 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));

1 个答案:

答案 0 :(得分:3)

不确定问题是什么。您可以将Button字面翻译成a ?? b的树。如果有疑问,请使用C#编译器编译表达式并查看它的作用。

http://tryroslyn.azurewebsites.net/#f:r/K4Zwlgdg5gBAygTxAFwKYFsDcAoUlaIoYB0AMpAI7ECiAHgA4BOqI4A9hCDvcAEYA2YAMYwh/AIasYAYRgBvbDCUweA4TABubMABMYAWQAUASnmLlFukxbsIAHgBiwCELspG+AHyeY4mAF4YEwCfACJQmAB+SJhwnAsAX2wEoAA=

与此同时,您已经询问如何编译Expression.Coalesce。答案是一样的:只需反编译现有代码即可查看输出内容。使用?: