C# Session.Add("key",value) 和 Session["key"] = value 有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10017962/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What's the Difference between Session.Add("key",value) and Session["key"] = value?
提问by Chandan Kumar
Can somebody please explain to me the difference between:
有人可以向我解释以下之间的区别:
Session.Add("name",txtName.text);and Session["name"] = txtName.text;
Session.Add("name",txtName.text);和 Session["name"] = txtName.text;
It was an interview question and I answered that both store data in key = "Value"format like Dictionaryclass in C#.
这是一个面试问题,我回答说两者都以key = "Value"类似于DictionaryC# 中的类的格式存储数据。
Am I right, or is there any difference?
我是对的,还是有什么区别?
采纳答案by Sean Kearney
Looking at the code for HttpSessionStateshows us that they are in fact the same.
查看代码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;
}
}
...
}
As for them both
至于他们俩
Storing data in
key = "Value"format likeDictionaryclass in C#.
以
key = "Value"类似DictionaryC# 中的类的格式存储数据。
They actually store the result in an IHttpSessionStateobject.
它们实际上将结果存储在一个IHttpSessionState对象中。
回答by KP.
The two code snippets you posted are one and the same in functionality. Both update (or create if it doesn't exist) a certain Sessionobject defined by the key.
您发布的两个代码片段在功能上是相同的。两者都更新(如果不存在则创建)Session由键定义的某个对象。
Session.Add("name",txtName.text);
Session.Add("name",txtName.text);
is the same as:
是相同的:
Session["name"] = txtName.text;
Session["name"] = txtName.text;
The first is method-based,where the second is string indexer-based.
第一个是method-based,第二个是 string 的地方indexer-based。
Both overwrite the previous value held by the key.
两者都覆盖键所持有的先前值。

