本地修改时会话变量得到更新

Session variable gets updated when modifying locally

为什么我的会话变量在我只在局部变量中修改时会更新。如果他们共享相同的引用,那么我想知道为什么它只在这种情况下更新而不在我使用类似代码的任何其他情况下更新。

 private void AddRefCodeToDTandConvertUnitValue(string StrRefCode)
        {
            DataTable dt = new DataTable();
            dt = Session["dataTable"] as DataTable;
            if (!dt.Columns.Contains("refCode"))
                dt.Columns.Add("refCode", typeof(String));
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                dt.Rows[i]["refCode"] = StrRefCode;
                if (DrpUnits.Items.FindByText(dt.Rows[i]["Units"].ToString()) != null)
                dt.Rows[i]["Units"] = DrpUnits.Items.FindByText(dt.Rows[i]["Units"].ToString()).Value;                                
            }
        }

我在我的一个网络应用程序中遇到了同样的问题。

这是因为当您将 Session 值类型转换为 DataTable 时,它​​将指向相同的内存位置。

为避免更新 Session 变量,您可以在类型转换时深度克隆它。它将在另一个具有相同值的内存位置创建另一个 DataTable 实例。