2010-09-08 77 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