2010-09-08 80 views
1

大家好我有一個實用程序類中的函數,它返回當前會話的用戶ID。 它拋出未設置爲對象實例的對象引用?我如何檢查它爲空&刪除此錯誤?在返回之前檢查會話嗎?

public static string GetSessionUserID 
{ 
    get 
    { 
     string userID = ""; 
     if (System.Web.HttpContext.Current.Session["userID"].ToString() != null) 
     { 
      userID = System.Web.HttpContext.Current.Session["userID"].ToString(); 
     } 
     if (userID == null) 
     { 
      throw new ApplicationException("UserID is null"); 
     } 
     else 
      return userID; 
    } 
} 

回答

6
object userID = System.Web.HttpContext.Current.Session["userID"]; 
if (userID == null) 
{ 
    throw new ApplicationException("UserID is null"); 
} 
return userID.ToString(); 

如果存儲在會話對象其實已經是一個字符串,你可以用ToString免除。錯誤的原因很簡單,你不能在空引用上調用ToString。這就是爲什麼上述檢查之前這樣做。

+0

感謝馬修。解釋真的很有幫助。你的意思是代替var嗎? – 2010-09-08 05:02:20

+0

@Popo,它們應該是等價的(編譯器會用'object'替換'var')。不過,我同意在這裏「對象」更清晰。 – 2010-09-08 05:22:44

+0

謝謝馬修。我prev。思想變量只存在於JavaScript中。 – 2010-09-08 07:17:45

0

用 「嘗試」,而不是 「如果」

string userID = ""; 
try{ 
      userID = System.Web.HttpContext.Current.Session["userID"].ToString(); 
} 
catch{ 
      throw new ApplicationException("UserID is null"); 
} 
return userID; 
+1

^^這是不鼓勵,爲什麼添加一個不必要的嘗試catch塊時,否則可以處理.. – Dienekes 2010-09-08 08:01:53

+0

@Dienekes這是一個有趣的點,但主題。請參閱視頻http://www.youtube.com/watch?v=XcTKR_QhEoE。那裏已經完成了基準測試的測試。以及http://stackoverflow.com/questions/1347848/c-real-time-try-catch不知何故,我同意你的看法,但並不總是必要的。 – 2010-09-09 04:48:43