2017-01-30 81 views
0

我有一个List<MemberBindings>我检查特定属性。 根据属性,我想检查表达式并判断是保留还是丢弃绑定。检查是否设置了MemberBinding的表达式或为空

目前,我有以下几点:

foreach(var memberBinding in memberBindings) 
{ 
    // ... check for attributes 
    var theExpression = ((MemberAssignment)memberBinding).Expression; 
    // ... check if not set and skip 
} 

,我要检查,如果theExpression为空(意味着未设置),但我不明白这一点。 在DebugView中,它显示{null}的- memberBinding的属性。

theExpression == null也不theExpression.Equals(null)返回true。也试过theExpression == Expression.Constant(null)/theExpression.Equals(Expression.Constant(null)),结果相同。

我在这里错过了什么?

**更新(调试视图的屏幕截图加入)**

enter image description here

+0

什么是在监视窗口中查看每个对象表达的价值观?即将手表添加到memberBindings中。另外你为什么要将该对象投射到MemberAssignment。这些是基类的子类型吗? – Wheels73

+0

@ Wheels73更新我的问题,并添加了调试视图的屏幕截图,其中显示了问题 – KingKerosin

回答

1

MemberAssignment表达的Expression属性是从未null。当它代表空值赋值时,它将是ConstantExpression类型,其中Value属性为null

然而,Expression类没有重载既不==运营商也不Equals方法,因此它相比,参考,这就是为什么

theExpression == Expression.Constant(null) 

theExpression.Equals(Expression.Constant(null)) 

不工作(Expression.Constant回报一个新的表达参考)。

相反,你需要检查,如果表达式实例ConstantExpression型(通过使用NodeType财产或is运营商要么),如果是,投它并检查Value财产。

像:

if (theExpression.NodeType == ExpressionType.Constant && 
    ((ConstantExpression)theExpression).Value == null) 

if (theExpression is ConstantExpression && 
    ((ConstantExpression)theExpression).Value == null) 

as操作:

var constExpression = theExpression as ConstainExpression; 
if (constExpression != null && constExpression.Value == null) 
+0

中的MemberBinding的内容,或者对于C#7更好,如果(表达式是ConstantExpression ce && ce.Value == null) –