【问题标题】:Possible NullreferenceException可能的 NullreferenceException
【发布时间】:2011-01-23 17:43:26
【问题描述】:

Resharper 显示“可能的 System.NullReferenceException”警告。但是,我看不到如何获得。

public class PlaceController : PlanningControllerBase
{
    [Authorize]
    public ActionResult StartStop(int id)
    {
        if (Request != null && Request.Cookies != null && Request.Cookies["place"] != null)
        {
            if (Request.Cookies["place"].Value != null)//Possible NullReferenceException?
            {
                string placeInformation = Request.Cookies["place"].Value;//Possible NullReferenceException?
                //...
            }
        }
    }
}

如果我检查所有字段,这如何给出 NullReference?使用以下内容不会显示警告:

Request.Cookies[0];//Index instead of name

编辑:更新代码。

【问题讨论】:

  • Request.Cookies["place"].Value 为空时,您是否有理由要设置变量placeInformation 或者这是一个错误?

标签: c# resharper nullreferenceexception


【解决方案1】:

我假设检查器没有检查传递给 CookieCollection 索引器的字符串的值是否每次都相同。我想如果您将代码重组为:

if (Request != null && Request.Cookies != null) 
{
    var place = Request.Cookies["place"];
    if (place != null && place.Value == null) 
    { 
        string placeInformation = place.Value;
    } 
}

它可能会起作用。

【讨论】:

    【解决方案2】:

    你不想要Request.Cookies["place"].Value != null ,现在您只需将 placeInformation 设置为 null。

    【讨论】:

      【解决方案3】:

      您不需要听取每一个警告。 Request 对象和 Cookies 对象永远不会为空,所以这就是您所需要的。

      var placeCookie = Request.Cookies["place"]; 
      if (placeCookie != null)
      {
          string placeInformation = placeCookie.Value;
      }
      

      【讨论】:

      • 确实,就是写"HttpCookie cookie = Request.Cookies["place"];"有效且不显示任何警告。
      • @Carra - 只是一个旁注,我认为在你的日常词汇中使用确实很棒。
      • 英语不是我的母语。我的意思是使用“是的,...”。
      • @Cara - 我并不是在暗示你的英语不正确。我只是说我确实出于某种奇怪的原因喜欢这个词。
      猜你喜欢
      • 1970-01-01
      • 2012-10-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多