【问题标题】:make new object from another object without change in new one when i changed in old one当我更改旧对象时,从另一个对象创建新对象而不更改新对象
【发布时间】:2011-12-19 21:54:13
【问题描述】:

我有 parent 类型的 Border 对象,我想让新对象 temp 等于 parent 但我可以在 parent 中更改而不更改 temp

如果我写Border temp = parent

如果我在parent 中更改了任何内容,temp 中的任何内容都会更改

如果我写Border temp = new border(parent)

如果我在 parent 中更改了任何内容,temp 中的内容也会更改

这两种方法是错误的,我想要它而不改变温度

边框类:

int x;
        int y;
        string name;
        List<Element> Border_elements;
        Point[] Border_border;
        BorderUnits[,] borderunitsvalue;
        int Numberofunits;

borderunits 类:

bool isempty;
        int currentelementid;
        int x;
        int y;
        List<int> visitedelementsid;

【问题讨论】:

标签: c# object


【解决方案1】:

您需要将父级克隆为临时。

有几种方法可以做到这一点:

1) 使用MemberwiseClone进行浅拷贝

public Border Clone()
{
   return (Border)this.MemberwiseClone();
}

2) 通过序列化对象然后将其反序列化到新实例来执行深度复制。为此,我们使用以下方法:

    /// <summary>
    /// This method clones all of the items and serializable properties of the current collection by 
    /// serializing the current object to memory, then deserializing it as a new object. This will 
    /// ensure that all references are cleaned up.
    /// </summary>
    /// <returns></returns>
    /// <remarks></remarks>
    public static T CreateSerializedCopy<T>(T oRecordToCopy)
    {
        // Exceptions are handled by the caller

        if (oRecordToCopy == null)
        {
            return default(T);
        }

        if (!oRecordToCopy.GetType().IsSerializable)
        {
            throw new ArgumentException(oRecordToCopy.GetType().ToString() + " is not serializable");
        }

        System.Runtime.Serialization.Formatters.Binary.BinaryFormatter oFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

        using (System.IO.MemoryStream oStream = new System.IO.MemoryStream())
        {
            oFormatter.Serialize(oStream, oRecordToCopy);
            oStream.Position = 0;
            return (T)(oFormatter.Deserialize(oStream));
        }
    }

可以这样称呼:

public Border Clone()
{
   return CreateSerializedCopy<Border>(this);
}

【讨论】:

  • 我的对象具有不可序列化的属性,所以不允许第二种方式第一种方式仍然在临时对象中更改!
【解决方案2】:

您想要克隆或复制对象。

在 C# 中,当您将变量分配给对象时,您只是引用该对象。该变量不是对象本身。当您将一个变量分配给另一个变量时,您最终会得到两个变量引用同一个对象。

使一个对象与另一个对象相同的唯一方法是创建一个新对象并复制另一个对象的所有状态。您可以通过 MemberwiseClone、Copy 方法、自己分配变量等方式来完成此操作。

(注意结构不同)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-26
    • 1970-01-01
    • 2021-07-24
    • 1970-01-01
    • 2019-03-12
    • 2010-10-22
    • 1970-01-01
    相关资源
    最近更新 更多