2011-10-10 80 views
1

此代碼拋出了一個錯誤:ASP.NET C#布爾型鑄造

bool status1 = (bool)Cache["cache_req_head"]; 
    bool status2 = (bool)Cache["cache_super"]; 
    bool status3 = (bool)Cache["cache_head"]; 

這是怎樣的緩存變量設置:

if (checkreqhead == true) 
     { 
      Cache["cache_req_head"] = true; 
     } 
     else if (checksuper == true) 
     { 
      Cache["cache_super"] = true; 
     } 
     else if (checkhead == true) 
     { 
      Cache["cache_head"] = true; 
     } 

即將從PHP的背景下,這是尷尬。錯誤是:

Object reference not set to an instance of an object

我確定這是一件非常簡單的事情,但可能我不能發現它。

感謝所有幫助:)

+0

順便說一句:你的if語句中的「== true」是多餘的。 – JohnFx

回答

4

「不設置到對象的實例對象引用」是C#行話「你做了一件愚蠢的一個null值」

如果緩存是空的你需要檢查第一

bool status1 = (bool)Cache["cache_req_head"]; 

應該

bool status1 = false; 
if (Cache["cache_req_head"] != null) 
{ 
    status1 = (bool)Cache["cache_req_head"]; 
} 

這是c#中的值類型(如bool,int等)不能爲空的事實的結果。有一個包裝,Nullable<T>與簡寫T?,你可以使用,如果你想允許爲值類型的空值。

您可以將您的值轉換爲bool?,因爲它允許null

bool? status1 = (bool?)Cache["cache_req_head"]; 

就可以檢查status1 == nullstatus1.HasValue,得到你需要挑選出來與status1.Value實際布爾值。如果您選擇status1.Valuestatus1 == null您將得到一個運行時異常,就像剛纔那樣。

+0

我還沒有嘗試過最後一件事,但它會起作用嗎?我想你會需要說:布爾? status1 = Cache [「cache_req_head」]爲bool? –

+0

@MikeChristensen,我的測試代碼'object oBool = null; \t \t \t bool? nBool = oBool as bool? \t \t \t Console.WriteLine(nBool); \t \t \t oBool = false; \t \t \t nBool = oBool as bool?; \t \t \t Console.WriteLine(nBool);'似乎工作正常。 –

+0

@MikeChristensen'as bool'將不起作用,因爲'T'需要'T'作爲參考類型。 (怎麼可能'as',否則返回null時,類型是不正確的?) –

1

顯然,您一次只能設置其中一個緩存條目。所以除非你只用1個變量設置爲true來運行「setter」代碼3次,那麼你總是會返回空值。 null不會投入bool,因爲它的值類型。嘗試使用bool?

0

由於Cache []返回一個對象,如果未設置,該對象爲null,那麼您會收到一個異常,試圖將null轉換爲bool。

您必須先檢查該鍵是否存在,或者您必須將每個鍵設置爲「false」作爲默認值。

2

其實,以檢查值是否存在在Cache最好的辦法是這樣做的:

//string is used as an example; you should put the type you expect 
string variable = Cache["KEY"] as string; 

if(variable!=null) 
{ 
    // do something 
} 

爲什麼做if(Cache["KEY"]!=null) myVariable=Cache["Key"];是不安全的原因,是因爲存儲在Cache["Key"]對象可能被刪除Cache,然後纔有機會將其分配給myVariable,並且最終認爲myVariable包含非空值。

+0

好點的伴侶 –