當我將一個自定義類的實例放入Session並將其拉出時,我需要將其作爲Session中COPY的一部分來提供,而不是Session中的內容的引用。這是我所擁有的,爲了舉例而淡化。在會話中複製/克隆對象
protected void btnSubmit_Click(object sender, EventArgs e)
{
Company selectedCompany = new Company("1234"); //a company code
selectedCompany.AnotherClass.Value1 = "hello";
Session["OLD.Company"] = selectedCompany;
Company newCompany = (Company)Session["OLD.Company"]; //I want this to be a COPY of what's in Session, not a reference to it.
newCompany.AnotherClass.Value1 = "goodbye";
Session["NEW.Company"] = newCompany;
}
我帶臺階的貫通,並觀看了Session變量,並在AnotherClass.Value1上面的代碼的結果對於這兩個OLD.Company和NEW.Company被設置爲「再見」。
最初的Google搜索指向我在公司課上實施IClonable的方向。我嘗試以下,但無濟於事:
public class Company : ICloneable
{
//properties...
//constructors...
public object Clone()
{
return this.MemberwiseClone();
}
}
然後......
protected void btnSubmit_Click(object sender, EventArgs e)
{
Company oldCompany = (Company)Session["OLD.Company"];
Company newCompany = (Company)oldCompany.Clone();
newCompany.AnotherClass.Value1 = "goodbye";
Session["NEW.Company"] = newCompany;
}
仍然導致值1兩種OLD.Company和NEW.Company是「再見」。現在我懷疑這是因爲MemberwiseClone()創建了一個「淺」副本,我的問題在於Value1是屬性中的一個值,該屬性是引用類型(AnotherClass)。
但是與此同時,我還發現this site其中說不執行ICloneable。因此,爲了我的目的,我不確定要做什麼/有什麼建議。
其他幾個網站,我發現了一些演出的版本是:
public static object CloneObject(object obj)
{
using (MemoryStream memStream = new MemoryStream())
{
BinaryFormatter binaryFormatter = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.Clone));
binaryFormatter.Serialize(memStream, obj);
memStream.Seek(0, SeekOrigin.Begin);
return binaryFormatter.Deserialize(memStream);
}
}
這就要求我把我的類序列化---這也許是好的(我必須要在系列化讀了),但在閱讀關於不使用ICloneable的文章後,我不確定是否應該花時間追求ICloneable解決方案。
+1複製構造是最直接的方法。 –
+1對一個普通問題的簡單回答 – rro
謝謝,我在問問題之前實際上已經嘗試了一個副本構造函數,但我想我現在看到我的問題在哪裏:我需要其他副本構造函數作爲其他實例的字段類。我之前做過的(不起作用的)是這個。其他類別= other.AnotherClass。我認爲這需要this.AnotherClass = new AnotherClass(other.AnotherClass),其中AnotherClass本身有它自己的拷貝構造函數。只是在這裏大聲思考。但是,謝謝澄清這是追求的正確道路。關於這一點,谷歌周圍的信息非常混亂。 – CptSupermrkt