[英]How to use Expressions to check for !=null against user-defined data types?
I'm new to expressions. 我是表达的新手。 I'm trying this and it doesn't seem to work.
我正在尝试这个,它似乎没有用。
ParameterExpression pe = Expression.Parameter(typeof(Customer));
Expression left = Expression.Property(pe, "OrderList");
Expression right = Expression.Constant(null, typeof(Nullable));
Expression res = Expression.NotEqual(left, right);
I'm gettign an "InvalidOperationException". 我得到一个“InvalidOperationException”。 In simple If-Else statement is look like this
简单的If-Else语句看起来像这样
if(custObj.OrderList != null)
{...}
Any help would be great. 任何帮助都会很棒。
Simply use 简单地使用
Expression right = Expression.Constant(null, left.Type);
It will give you the null
constant with the same type as the left operand (property in your case). 它将为您提供与左操作数相同类型的
null
常量(在您的情况下为property)。
The problem is you are comparing objects of different types. 问题是您正在比较不同类型的对象。 You can solve this by using
Expression.Constant(object value)
overload, I'm assuming that the type of the property OrderList
is by reference, if not you can't do this comparison. 你可以通过使用
Expression.Constant(object value)
重载来解决这个问题,我假设属性OrderList
的类型是通过引用,如果不是你不能做这个比较。
ParameterExpression pe = Expression.Parameter(typeof(Customer));
Expression left = Expression.Property(pe, "OrderList");
Expression right = Expression.Constant(null);
Expression res = Expression.NotEqual(left, right);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.