当对象在C#中更新会话对象更改 [英] Session object changes when object is updated in C#

查看:193
本文介绍了当对象在C#中更新会话对象更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这篇关于当对象在C#中更新会话对象更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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