Jor*_*rdi 2 c# linq linq-expressions null-propagation-operator
我想用Expression树生成这个句子:
o?.Value
Run Code Online (Sandbox Code Playgroud)
o 是任何一个类的实例.
有什么办法吗?
通常,如果要执行如何为某个表达式构造表达式树,可以让C#编译器执行此操作并检查结果.
但在这种情况下,它将无法工作,因为"表达式树lambda可能不包含空传播运算符".但是你实际上并不需要null传播运算符,你只需要一些行为类似的东西.
你可以通过创建类似如下的表达式:o == null ? null : o.Value.在代码中:
public Expression CreateNullPropagationExpression(Expression o, string property)
{
Expression propertyAccess = Expression.Property(o, property);
var propertyType = propertyAccess.Type;
if (propertyType.IsValueType && Nullable.GetUnderlyingType(propertyType) == null)
propertyAccess = Expression.Convert(
propertyAccess, typeof(Nullable<>).MakeGenericType(propertyType));
var nullResult = Expression.Default(propertyAccess.Type);
var condition = Expression.Equal(o, Expression.Constant(null, o.Type));
return Expression.Condition(condition, nullResult, propertyAccess);
}
Run Code Online (Sandbox Code Playgroud)