检查Null异常的正确方法是什么?

Ste*_*ice 5 c# asp.net

哪个代码最正确?

if (HttpContext.Current.Response.Cookies[authCookieName] != null) {
    HttpContext.Current.Response.Cookies[authCookieName].Value = "New Value";
}
Run Code Online (Sandbox Code Playgroud)

要么

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";
Run Code Online (Sandbox Code Playgroud)

yfe*_*lum 19

如果HttpContext,HttpContext.Current,HttpContext.Current.Response或Http.Current.Response.Cookies中的任何一个为空,那么您已经遇到了麻烦.让异常发生并修复您的Web服务器.


Kri*_*erA 5

两者都很好。假设您已经检查了所有其他需要先检查的内容。例如:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

(对不起,无法抗拒... :) )