通过httpcache循环c#

Qui*_*011 6 c# asp.net vb.net-to-c#

在VB.NET上我可以做这样的事情来写出缓存中的所有密钥:

Dim oc As HttpContext = HttpContext.Current

For Each c As Object In oc.Cache
    oc.Response.Write(c.Key.ToString())
Next
Run Code Online (Sandbox Code Playgroud)

尽管.Key没有出现在Intellisense中,但代码运行得很好.

我如何在c#中做同样的事情?

HttpContext oc = HttpContext.Current;
foreach (object c in oc.Cache) 
{
    oc.Response.Write(c.key.ToString());
}
Run Code Online (Sandbox Code Playgroud)

它不喜欢.key.位.我在这里不知所措.有任何想法如何以这种方式访问​​密钥?

Ode*_*ded 11

差不多吧-这是一个资本KKey,而不是小写.C#区分大小写.

此外,object没有Key会员.在C#中,您也可以使用隐式类型推断和var关键字.如果基础推断类型具有Key成员,则此方法将起作用:

HttpContext oc = HttpContext.Current;

foreach (var c in oc.Cache) 
{
    oc.Response.Write(c.Key.ToString());
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,Cache没有Key成员,所以你需要深入挖掘,使用IDictionaryEnumerator以下GetEnumerator方法返回Cache:

HttpContext oc = HttpContext.Current;

IDictionaryEnumerator en = oc.Cache.GetEnumerator();
while(en.MoveNext())
{
    oc.Response.Write(en.Key.ToString());
}
Run Code Online (Sandbox Code Playgroud)


Eli*_*ain 9

下面代码snap工作正常:

HttpContext oc = HttpContext.Current;
foreach (var c in oc.Cache)        
{
   oc.Response.Write(((DictionaryEntry)c).Key.ToString());
}
Run Code Online (Sandbox Code Playgroud)

谢谢你的时间