什么';s Session.Add(“key”,value)和Session[“key”]之间的差值=value

本文关键字:key value Session 之间 Add 什么 | 更新日期: 2023-09-27 18:29:57

有人能向我解释一下之间的区别吗

Session.Add("name",txtName.text);Session["name"] = txtName.text;

这是一个采访问题,我回答说两者都以key = "Value"格式存储数据,就像C#中的Dictionary类一样。

我是对的,还是有什么不同?

什么';s Session.Add(“key”,value)和Session[“key”]之间的差值=value

查看HttpSessionState的代码可以发现它们实际上是相同的。

public sealed class HttpSessionState : ICollection, IEnumerable
{
    private IHttpSessionState _container;
...
    public void Add(string name, object value)
    {
        this._container[name] = value;
    }
    public object this[string name]
    {
        get
        {
            return this._container[name];
        }
        set
        {
            this._container[name] = value;
        }
    }
...
}

至于他们两个

key = "Value"格式存储数据,类似于C#中的Dictionary类。

它们实际上将结果存储在IHttpSessionState对象中。

您发布的两个代码片段在功能上是相同的。两者都会更新(或在不存在的情况下创建)由键定义的某个Session对象。

Session.Add("name",txtName.text);

与相同

Session["name"] = txtName.text;

第一个是method-based,,其中第二个是字符串indexer-based

两者都会覆盖键所保持的上一个值。