gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 21:56:40 25 4
gpt4 key购买 nike

检查表达式树中常量是否为 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));

最佳答案

不确定是什么问题。你可以翻译 a ?? b 使用 Expression.Coalesce 从字面上变成一棵树。如果有疑问,请使用 C# 编译器编译表达式并查看它做了什么。

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

同时你问了如何编译?:。答案是一样的:简单地反编译现有代码以查看输出的内容。使用 Expression.Condition

关于c# - 检查表达式树中值是否为空的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31336343/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com