简体   繁体   中英

Assign one session to another session for same Class in C#

I have create 2 session for same class.

    public static Breadcrumb Breadcrumb
    {
        get { return HttpContext.Current.Session["Breadcrumb"] != null ? (Breadcrumb)HttpContext.Current.Session["Breadcrumb"] : null; }
        set { HttpContext.Current.Session["Breadcrumb"] = value; }
    }

    public static Breadcrumb ChildBreadcrumb
    {
        get { return HttpContext.Current.Session["ChildBreadcrumb"] != null ? (Breadcrumb)HttpContext.Current.Session["ChildBreadcrumb"] : null; }
        set { HttpContext.Current.Session["ChildBreadcrumb"] = value; }
    }

and the class used for session is as below

[Serializable]
public class Breadcrumb
{
    public string project { get; set; }
    public int projectId { get; set; }
}

I'm assigning Breadcrumb to ChildBreadcrumb only once in one event.

But ChildBreadcrumb updates all time when Breadcrumb is changed after assignment.

How can I prevent this automatic update?

Sessions aren't serialised until the end of the page lifecycle, where they are saved. That means these two references point to the same object until then.

Essentially you are doing this:

var A = new Breadcrumb { project = "original" };

var B = A;

B.project = "change";

As Breadcrumb is a class these are reference types - both A and B are references to the same Breadcrumb

To avoid that make a copy of Breadcrumb when you assign it to ChildBreadcrumb , something like:

var A = new Breadcrumb { project = "original" };

var B = new Breadcrumb { project = A.project, projectId = A.projectId };

B.project = "change";

Now B is an independent copy.

Note that project is an immutable string and projectId is a value type int , so they don't behave the same way as Breadcrumb .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM