阻止作为其他会话值列表的会话进行重写



在ASP.Net web表单应用程序中,我考虑一个会话:

((List<clsSharedVariables>)HttpContext.Current.Session["ListVariables"])

每次点击菜单项,我都会将用户重定向到一个新的选项卡,在重定向之前,我会将当前会话保存在此列表中:

clsSharedVariables currentSession = new clsSharedVariables();
currentSession = (clsSharedVariables)HttpContext.Current.Session["SharedVariables"];
var ListSharedVariables = ((List<clsSharedVariables>)HttpContext.Current.Session["ListVariables"]);
var currentTabId = ListSharedVariables.Count + 1;
currentSession.CurrentTabId = currentTabId;
if (!ListSharedVariables.Contains(currentSession))
{
ListSharedVariables.Add(currentSession);
HttpContext.Current.Session["ListVariables"] = ListSharedVariables;
}

问题是,当我单击菜单中的每个项目时,ListVariables中的所有项目都会更新为最后一个会话值。我不明白是怎么回事,为什么;因为列表是独立的,外部值不能更改列表中的值。例如,在上面的代码中,当我设置:

currentSession.CurrentTabId = currentTabId;

HttpContext.Current.Session["ListVariables"]中旧项的currentTabId更改为这个新值,我认为这是一个很大的错误。

你能理解问题出在哪里吗?这些价值观之间有什么错误的联系?

这是因为您的列表List<clsSharedVariables>中只有对clsSharedVariables-类的一个实例的引用
当您更改该实例的一个属性的值时,所有引用也会发生更改,因为它们只是指向该实例。

在这里,您可以从会话中获得您的实例:
currentSession = (clsSharedVariables)HttpContext.Current.Session["SharedVariables"];

因此,您只需使用
ListSharedVariables.Add(currentSession);向列表添加一个引用

为了避免这种情况,您可以为clsSharedVariables使用结构而不是类,因为结构是一种值类型。

有关值和引用类型差异的更多信息,请参阅本文

最新更新