当对象在C#中更新会话对象更改对象

2023-09-05 00:17:42 作者:幼崽

我有一个很奇怪的问题,我敢肯定,我失去了一些东西在这里很明显。我有以下两行:

I have this really weird problem and I'm sure I'm missing something obvious here. I have these two lines:

HttpContext.Current.Session[listModelType + "ListModel"] = listModel;
listModel.ProductRows = new Collection<ProductRow>(listModel.ProductRows.Where(r => r.ParentRowId == 0).ToList());

执行第二行后,我的会话对象被更新以及(据观察在Visual Studio)

After the second line is executed my session object is updated as well (according to "Watch" in Visual Studio)

我是什么在这里失踪?

我已经试过

int i = 0;
HttpContext.Current.Session["i"] = i;
i++;

和HttpContext.Current.Session [我]保持为0。

and HttpContext.Current.Session["i"] remains 0.

推荐答案

见的值类型和引用类型的。

INT 那么将存储原样关于分配的力矩的值类型;你的的ListModel 是引用类型,所以你存储一个参考对象在会话,对象不是值。

The int is a value type so will be stored "as-is" on the moment of assignment; your listModel is a reference type so you store a reference to the object in your session, not the value of the object.

您将有,如果你想一个在会话不变创建的ListModel 一个新的实例。

You'll have to create a new instance of listModel if you want the one in your session untouched.

 
精彩推荐
图片推荐