在Session中复制/克隆对象

时间:2012-11-20 01:54:32

标签: c# asp.net class object cloneable

当我将一个自定义类的实例放入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 for BOTH OLD.Company和NEW.Company被设置为“goodbye。”

最初的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;
}

仍然导致BOTH OLD.Company和NEW.Company的Value1为“再见”。现在我怀疑这是因为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 个答案:

答案 0 :(得分:3)

您的问题与Session对象无关。你只需要制作一个对象的副本吗?

以下是编写复制构造函数的方法:

http://msdn.microsoft.com/en-US/library/ms173116%28v=VS.80%29.aspx

class Company 
{
...
  public Company (Company other)
  { 
    // copy fields here....
  }
}