2014-02-19 25 views
1

在像OperationContext一个复杂的对象是安全的写这样的代码:检查空的层次结构中的if语句

if(OperationContext.Current!=null && 
    OperationContext.Current.ServiceSecurityContext !=null && 
    OperationContext.Current.ServiceSecurityContext.WindowsIdentity !=null) 

或者我需要到代码中分离到三个if报表?

我的问题是如果OperationContext.Current为空我恐怕OperationContext.Current.ServiceSecurityContext会抛出NullReferenceException

回答

4

C#中的&&运算符使用short circuit evalulation所以你的代码很好。

这是什么意思是条件的左侧首先评估,如果它通过右侧,然后评估。

+0

什么是电路评估? –

+1

@ilayzeidman我在我的回答中解释过。此外,我提供的链接将为您提供您需要了解的一切。 – James

3

这是安全的。 &&的右侧仅在左侧是true时才被评估。

这里是MSDN explanation

操作

x && y 

对应于操作

x & y 

不同之处在于,如果x是假,y为未评价,因为结果 无论y的值是多少,AND运算都是错误的。这是 被称为“短路”评估。

+0

所以顺序很重要? –

+1

@ilayzeidman,是的。如果你交换操作数,'Current'为空,你将会有一个例外 – Andrei