简体   繁体   English

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

[英]Best way to check if value is null in Expression Tree

What is the best way to check if constant is null in 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_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));

Not sure what the problem is. 不确定是什么问题。 You can translate a ?? b 您可以翻译a ?? b a ?? b literally into a tree with Expression.Coalesce . a ?? bExpression.Coalesce从字面上看成一棵树。 If in doubt compile an expression with the C# compiler and look at what it did. 如果有疑问,请使用C#编译器编译表达式,然后查看其效果。

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

Meanwhile you have asked how to compile ?: . 同时,您问如何编译?: The answer is the same: Simply decompile existing code to see what is being output. 答案是相同的:只需反编译现有代码即可查看正在输出的内容。 Use Expression.Condition . 使用Expression.Condition

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM