哪个是检查Null异常的正确方法?
哪一个是最正确的代码?哪个是检查Null异常的正确方法?
if (HttpContext.Current.Response.Cookies[authCookieName] != null) {
HttpContext.Current.Response.Cookies[authCookieName].Value = "New Value";
}
或
if (HttpContext.Current != null)
if (HttpContext.Current.Response != null)
if (HttpContext.Current.Response.Cookies != null)
if (HttpContext.Current.Response.Cookies[authCookieName] != null)
HttpContext.Current.Response.Cookies[authCookieName].Value = "New Value";
如果HttpContext的,HttpContext.Current,HttpContext.Current.Response中的任何一个,或Http.Current.Response.Cookies为空,你已经陷入困境。让异常发生并修复您的Web服务器。
虽然我会避免第二个问题,但它们都不是很正确,因为深嵌的条件往往难以理解和维护。
如果您希望获得空指针异常,请使用第一个。如果你想以另一种方式或默默地处理空值,使用第二个(或第二个的重构版本)。
如果你想有一个机会,Current
,Response
,Cookies
,或Cookies[authCookieName]
可能是null
,你有一件合理的事做,如果其中的任何一样,那么后者的路要走。如果机会很少,并且/或者如果中间体为空,那么就没有什么办法可以做,因为它更简洁 - 如果您使用扩展示例,最好做的是更好地记录日志。
可以尝试:
if(HttpContext.Current != null &&
HttpContext.Current.Response != null &&
HttpContext.Current.Response.Cookies != null &&
HttpContext.Current.Response.Cookies[authCookieName] != null)
{
// do your thing
}
HttpContext.Current.Response.Cookies永远不会为空。唯一可能导致null的是如果你期望的cookie不存在,那么第一个是正确的。 HttpContext.Current将为null如果你不接受一个web请求通过:)
两者都很好。假设你已经检查了所有需要首先检查的其他东西。例如: -
private bool CheckSuspendersAndBelt()
{
try
{
//ensure that true is true...
if (true == true)
{
//...and that false is false...
if (false == false)
{
//...and that true and false are not equal...
if (false != true)
{
//don't proceed if we don't have at least one processor
if (System.Environment.ProcessorCount > 0)
{
//and if there is no system directory then something is wrong
if (System.Environment.SystemDirectory != null)
{
//hopefully the code is running under some version of the CLR...
if (System.Environment.Version != null)
{
//we don't want to proceed if we're not in a process...
if (System.Diagnostics.Process.GetCurrentProcess() != null)
{
//and code running without a thread would not be good...
if (System.Threading.Thread.CurrentThread != null)
{
//finally, make sure instantiating an object really results in an object...
if (typeof(System.Object) == (new System.Object()).GetType())
{
//good to go
return true;
}
}
}
}
}
}
}
}
}
return false;
}
catch
{
return false;
}
}
(对不起,无法抗拒... :))
你给我的第一个例子是绰绰有余。就像上面提到的那样,如果其他任何对象都是空的,那么ASP.NET有问题。
if (HttpContext.Current.Response.Cookies[authCookieName] != null) {
HttpContext.Current.Response.Cookies[authCookieName].Value = "New Value";
}
但是比起这些往往是许多乱丢检查你的代码,你应该创建一些通用的功能,如的setcookie,的getCookie,GetQueryString,并GetForm等,这些接受的名称和值(用于设置函数)作为参数,处理空检查,并返回值或空字符串(用于获取函数)。这将使您的代码更容易维护并可能改进,如果您决定使用除Cookies之外的其他功能来存储/检索选项,则只需更改这些功能即可。
BTW:HttpContext是一个类。如果一个类是空的,你肯定有麻烦了! :P – yfeldblum 2008-10-03 03:17:39
诀窍问题.... drat! – craigmoliver 2008-10-03 04:36:07