C# - Using a copy of Session-stored variables instead of reference
I have an asp:ImageButton with OnClick="Btn_OnClick".
In Btn_OnClick I have this line:DataTable dtTable = (DataTable)Session["someSessionKey"]
and dtTable is altered in the functio开发者_如何转开发n.
I've noticed that if the button's clicked more than once, the dtTable I take from the session contains the altered table, probably meaning dtTable is not a copy but a reference of the session variable.
How can I alter a copy of Session["someSessionKey"], and not the actual value?
Thanks!DataTable dtTable = ((DataTable)Session["someSessionKey"]).Copy();
If the object in the Session implements ICloneable
, you can use var myCopy = mySessionObject.Clone();
. You would then have to read the documentation of the object to see what it exactly does.
This is because there is no generic solution to cloning. Mostly, objects have other non-scalar objects as properties, so it always depends on the scenario if you need to clone those child objects too.
When you author your own class, you can always call the protected MemberwiseClone()
method that is defined in System.Object
to get a flat clone. You can then choose if you want to add some additional cloning logic and if you want to make it available for callers outside.
If the object in the Session is a List<T>
or an IEnumerable<T>
, you can do var myCopiedList = new List<T>(myListInSession);
. Keep in mind that the individual objects in that list are not cloned in that case. You'd have to foreach
through them and clone each object manually. It's similar with the DataTable
. You might need to manually create a new instance and copy the content over.
To manually clone an object that doesn't support any public method to do so, you'd have to create a new instance of it. Then you'd assign every property from the original object to the cloned object manually. That can be not only tedious, often it also won't work because there are protected members that you can't access easily.
Finally, you can resort to reflection or other tricks to try to clone an object. A quick google search gave me that result: C# Object clone wars.
精彩评论