简体   繁体   中英

Serialization of objects and Reference Equality

Does the .NET runtime maintain object references when serializing to SQL Session State/InProc Session State; during serialization/deserialization? In the following example, I'd expect the references to point to the same object. Can someone explain why this isn't the case.

Eg:

var list = new List<Foo> { new Foo { Name = "foo" }, new Foo { Name = "bar" } };

var bar = list.Single(x => x.Name == "bar" );

Session["list"] = list;
Session["bar"] = bar;

var listDeserialized = (List<Foo>)Session["list"];
var barDeserialized = (Foo)Session["bar"];

Assert.IsTrue(Object.ReferenceEquals(listDeserialized[1], bar)); // false

/* class definition */
[Serializable]
public class Foo {
    public string Name { get; set; }
}

Note: Assume that the list and bar objects have already been serialized/persisted to SQL.

Yes because it uses BinaryFormatter for serialization which preserves the object tree as it was. See details here: http://msdn.microsoft.com/en-us/library/aa479041.aspx#aspnetsessionstate_topic5

Some methods on serialization, like XML and Soap, would definitely create 2 different objects after de-serializing; but Binary serialization, the one used to preserve Asp.Net Session State in SQL, does preserve the object tree and will make both references in your example point to the same physical object in memory.

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