为什么在Request.Cookies时foreach循环返回字符串代替的HttpCookie对象吗? [英] Why does Request.Cookies return string instead of HttpCookie object in foreach loop?

查看:345
本文介绍了为什么在Request.Cookies时foreach循环返回字符串代替的HttpCookie对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天早上我无意中看到下面的代码片段code,我相当惊讶,因为它工作得很好。

别看它的逻辑请,我只是好奇为何HttpCookieCollection(在这种情况下Request.Cookies时)返回一个字符串(cookie名称),而不是在foreach循环一个的HttpCookie对象。它是一个连贯的问题,因为我们通常得到的HttpCookie对象在此集合按索引/名称?

谢谢,

 的foreach(在System.Web.HttpContext.Current.Request.Cookies串cookieKey)
{
    的HttpCookie tmpCookie = System.Web.HttpContext.Current.Request.Cookies [cookieKey]
    如果(tmpCookie = NULL&放大器;!&安培;!tmpCookie [RecentlyVisited] = NULL)
    {
       cookie.Add(tmpCookie);
    }
}


解决方案

它更有意义通过按键集合进行迭代。这样,你可以访问两个按键,可以很容易通过调用访问值 System.Web.HttpContext.Current.Request.Cookies [cookieKey];

This morning I accidentally saw the following snippet code, I was fairly surprised because it work very well.

Don't look at its logic please, I'm just curious why does the HttpCookieCollection (Request.Cookies in this case) return a string (cookie name) instead of a HttpCookie object in foreach loop. Is it a consistency issue because we normally get HttpCookie object in this collection by index/name?

Thanks,

foreach (string cookieKey in System.Web.HttpContext.Current.Request.Cookies)
{
    HttpCookie tmpCookie = System.Web.HttpContext.Current.Request.Cookies[cookieKey];
    if (tmpCookie != null && tmpCookie["RecentlyVisited"] != null)
    {
       cookie.Add(tmpCookie);
    }
}

解决方案

It makes more sense to iterate through a collection by the keys. That way you have access to both the keys and can easily access the value by calling System.Web.HttpContext.Current.Request.Cookies[cookieKey];

这篇关于为什么在Request.Cookies时foreach循环返回字符串代替的HttpCookie对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆