2014-02-19 21 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