2

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

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

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

4

5 回答 5

3

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

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

于 2014-04-16T20:24:20.457 回答
2

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

if (HttpContext.Current != null &&
    (HttpContext.Current.Cache[Key] == null || string.IsNullOrEmpty(HttpContext.Current.Cache[Key].ToString()))
{
     HttpContext.Current.Cache[Key] = data;
}
于 2014-04-16T20:29:02.847 回答
1

您收到 NullReferenceException 是因为您试图调用ToString()一个null实例。

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

if (HttpContext.Current.Cache[Key] == null)
{
   HttpContext.Current.Cache[Key] = data;
}
于 2014-04-16T20:24:04.400 回答
0

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

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

Object_reference_not_set_to_an_instance_of_an_object错误”实际上本质上是我正在寻找的“空”值......

于 2014-04-16T20:24:48.913 回答
0

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

HttpContext.Current.Cache[Key]

然后,您会盲目地调用ToString()缓存中的值,从而导致异常。

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

于 2014-04-17T00:03:46.930 回答