哪种检查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中的任何一个为null,则我们已经遇到麻烦了。让异常发生并修复Web服务器。
两者都不是真正正确的,尽管我会避免使用第二个,因为嵌套的条件条件往往难以理解和维护。
如果我们希望得到一个空指针异常,请使用第一个。如果要以其他方式或者无声处理空值,请使用第二个(或者第二个的重构版本)。
如果我们认为"当前","响应"," 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。唯一会导致为null的是,如果我们所期望的cookie不存在,那么第一个是正确的。如果我们不接受Web请求,则HttpContext.Current将为null :)
两者都很好。假设我们已经检查了其他所有需要首先检查的内容。例如。:
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; } }
(对不起,无法抗拒... :))
我们提供的第一个示例已绰绰有余。如前所述,如果任何其他对象为null,则ASP.NET存在问题。
if (HttpContext.Current.Response.Cookies[authCookieName] != null) { HttpContext.Current.Response.Cookies[authCookieName].Value = "New Value"; }
但是,我们应该创建一些通用函数(例如SetCookie,GetCookie,GetQueryString和GetForm等),而不是通过这些经常进行的大量检查来填充代码,它们接受名称和值(对于Set函数)作为参数,处理null检查,并返回值或者空字符串(用于Get Functions)。这将使代码更易于维护并可能得到改进,并且如果我们以后决定使用Cookie以外的其他东西来存储/检索选项,则只需更改功能即可。