2011-01-26 69 views
0

哪個更好?C中的基本布爾邏輯#

this.isLoggedIn = (bool)HttpContext.Current.Session["li"] == true; 

this.isLoggedIn = (bool)HttpContext.Current.Session["li"]; 

它必須是真實的,只有當會話是真實的。如果會話設置爲false,那麼它會在#2中評估爲真,因爲它存在?還是評估其價值?

+0

可能重複的[Confusing If Statement?](http://stackoverflow.com/questions/2407617/confusing-if-statement) – 2011-04-13 05:53:40

回答

3

第二個:

this.isLoggedIn = (bool)HttpContext.Current.Session["li"]; 

(bool)HttpContext.Current.Session["li"]已經是一個布爾(因此將或者truefalse),所以不需要對布爾表達式的額外比較和返回值。無論哪種方式,您需要檢查li會話變量是否存在,然後再嘗試轉換它,否則您的代碼將拋出(我認爲是NullReferenceException)。

2

後者更清晰,IMO。儘管它們在功能上是等價的 - 在這兩種情況下,它都會從會話中獲取「li」的值,並嘗試將其轉換爲bool,如果值不存在則拋出異常。

+0

謝謝,所以他們都只是評估會議的價值,而不是評估如果會話變量是否存在? (Like Javascript) – 2011-01-26 10:40:18

+0

@Tom:是的 - 表達式`(bool)HttpContext.Current.Session [「li」];`將被評估。 – 2011-01-26 10:41:07

-1

這兩段代碼都是相等的,所以第二個代碼段越短越好。

0

第一種和第二種方法是等價的,但第一種方法是爲我的口味冗長。我更喜歡第二個。

正如我喜歡比

bool accepted = true; 
if(accepted == true) 
{ 
    .. 
} 

更好這個

bool accepted = true; 
if(accepted) 
{ 
    .. 
} 

我覺得更清楚這樣,如果變量都是正確的。

0

只要把預期值表達式的地方,它會變得非常清楚:

First example: 
Before: this.isLoggedIn = (bool)HttpContext.Current.Session["li"] == true; 
After: this.isLoggedIn = true == true; 

Second example: 
Before: this.isLoggedIn = (bool)HttpContext.Current.Session["li"]; 
After: this.isLoggedIn = true; 

現在,試着同爲false情況:

First example: 
Before: this.isLoggedIn = (bool)HttpContext.Current.Session["li"] == true; 
After: this.isLoggedIn = false == true; 

Second example: 
Before: this.isLoggedIn = (bool)HttpContext.Current.Session["li"]; 
After: this.isLoggedIn = false; 

,你可以看,這兩種方法的結果沒有什麼區別。這一切都歸結爲關於編碼風格和可讀性的問題,我猜想你會發現對較短版本的偏見。

0

你永遠不需要寫代碼說:

bool x =(y == true);

,而不是僅僅使用

bool x = y; 

在特定情況下,你應該使用:

this.isLoggedIn = HttpContext.Current.Session["li"] != null 
    && (bool)HttpContext.Current.Session["li"]; 

這樣,如果會議[「禮」]尚未分配,你不會得到一個例外。但是,如果Session [「li」]不能轉換爲bool,你會得到一個異常。

1

創建所需值的屬性:

public bool IsLoggedIn { 
    get { return (bool)HttpContext.Current.Session["li"]; } 
} 

你甚至可以去一個額外的水平,如果會話在課堂上使用了很多:

public bool IsLoggedIn { 
    get { return (bool)Session["li"]; } 
} 

private HttpSessionState Session { 
    get { return HttpContext.Current.Session; } 
} 

此外,如果你曾經想要單獨查看會話,請使用更好的密鑰,例如"IsLoggedIn",而不是"li"

這可能是件好事創建這些應用程序範圍內的值的特殊類:

public static class MyAppSession { 

    const string IsLoggedInKey = "IsLoggedIn"; 

    public static bool IsLoggedIn { 
    get { 
     return Session[IsLoggedInKey] != null && (bool)Session[IsLoggedInKey]; 
    } 
    internal set { Session[IsLoggedInKey] = value; } 
    } 

    // ... 

    private static HttpSessionState Session { 
    get { return HttpContext.Current.Session; } 
    } 

} 
0

我會用第二個選項具有一個變體:
this.isLoggedIn =(布爾)(HttpContext.Current .Session [「li」] ??「false」);

該??是null-coalescing operator - 它爲左側的表達式提供「false」值,以防碰巧爲空。