【问题标题】:Checking for null HttpContext.Current.Cache value检查空 HttpContext.Current.Cache 值
【发布时间】:2014-05-31 21:49:36
【问题描述】:

在下面的 sn-p 中,如果缓存值尚不存在,我将尝试分配缓存值。运行以下命令时出现 Object_reference_not_set_to_an_instance_of_an_object 错误。我错过了什么?

if (string.IsNullOrEmpty(HttpContext.Current.Cache[Key].ToString()))
                HttpContext.Current.Cache[Key] = data;

我在 SO 上环顾四周,但找不到类似的东西。也许我只是没有正确地表达我的问题。

【问题讨论】:

    标签: c# .net httpcontext.cache


    【解决方案1】:

    HttpContext.Current 可以为空。 HttpContext.Current.Cache[Key] 可能为空。

    如果其中任何一个为空,则会导致您遇到的错误。

    【讨论】:

    • 是的,这就是问题所在。
    【解决方案2】:

    您应该检查HttpContext.CurrentHttpContext.Current.Cache[Key] 上的null,这两个都可能为null。这是一个可能的解决方案,只要您可以在 HttpContext.Current 为空时不设置缓存键。

    if (HttpContext.Current != null &&
        (HttpContext.Current.Cache[Key] == null || string.IsNullOrEmpty(HttpContext.Current.Cache[Key].ToString()))
    {
         HttpContext.Current.Cache[Key] = data;
    }
    

    【讨论】:

      【解决方案3】:

      您收到 NullReferenceException 是因为您试图在 null 实例上调用 ToString()

      在调用ToString()之前,您必须检查HttpContext.Current.Cache[Key] 是否为null

      if (HttpContext.Current.Cache[Key] == null)
      {
         HttpContext.Current.Cache[Key] = data;
      }
      

      【讨论】:

      • 你是对的,这就是问题所在。我只是陷入了以一种方式做事......
      【解决方案4】:

      我刚刚更改了“获取值、转换为字符串、比较”逻辑以获取值并在前面查看它是否为空。傻我。

      if (HttpContext.Current.Cache[Key] == null)
             HttpContext.Current.Cache[Key] = data;
      

      Object_reference_not_set_to_an_instance_of_an_object 错误”实际上是我一直在寻找的“空”值...

      【讨论】:

        【解决方案5】:

        如果他们的密钥不存在,那么这将返回null

        HttpContext.Current.Cache[Key]
        

        然后,您在缓存中的值上盲目调用 ToString(),导致异常。

        在调用ToString()之前,您需要将缓存中的值分配给一个临时变量并测试null

        【讨论】:

          猜你喜欢
          • 2013-01-03
          • 2013-05-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-07-13
          • 2020-08-04
          • 2011-06-03
          相关资源
          最近更新 更多