ASP.NET
如何:检索缓存项的值

更新:2007 年 11 月

要从缓存中检索数据,应指定存储缓存项的键。不过,由于缓存中所存储的信息为易失信息,即该信息可能由 ASP.NET 移除,因此建议的开发模式是首先确定该项是否在缓存中。如果不在,则应将它重新添加到缓存中,然后检索该项。

检索缓存项的值

  • 通过在 Cache 对象中进行检查来确定该项是否不为 null(在 Visual Basic 中为 Nothing)。如果该项存在,则将它分配给变量。否则,重新创建该项,将它添加到缓存中,然后访问它。

    下面的代码示例演示如何从缓存中检索名为 CacheItem 的项。代码将该项的内容分配给名为 cachedString 的变量。如果该项不在缓存中,则代码会将它添加到缓存中,然后将它分配给 cachedString

    C#
    string cachedString;
    cachedString = (string)Cache["CacheItem"];
    if (cachedString == null)
    {
      cachedString = "Hello, World.";
      Cache.Insert("CacheItem", cachedString);
    }

    Visual Basic
    Dim cachedString As String
    cachedString = CStr(Cache("CacheItem"))
    If cachedString Is Nothing Then
      cachedString = "Hello, World."
      Cache.Insert("CacheItem", cachedString)
    End If
请参见

任务

概念

标记 :


Page view tracker