Duplicate Object and working with Duplicate without changing Original

后端 未结 8 590
逝去的感伤
逝去的感伤 2020-12-08 14:02

Assuming I have an Object ItemVO in which there a bunch of properties already assigned. eg:

ItemVO originalItemVO = new ItemVO();
originalItemVO.ItemId = 1;         


        
相关标签:
8条回答
  • 2020-12-08 14:21

    By Default objects are reference type.

    Assign the one object to another object its means that you just refer the address of the object.Any changes in any object it will reflect in both.

    To solve this problem you should have initialize the object using "new" keyword, then add this object value in the first object.

    0 讨论(0)
  • 2020-12-08 14:26

    I suggest using as is in the link below. For me it worked very well.

    https://msdn.microsoft.com/en-us/library/system.object.memberwiseclone(v=vs.110).aspx

     public Person ShallowCopy ()
     {
        return (Person) this.MemberwiseClone ();
     }
    
    0 讨论(0)
  • 2020-12-08 14:32

    In order to change one instance without changing the other you need to clone the actual values of this instance and not the reference. The pattern used in .Net is to implement ICloneable. So your code would look like this:

    public class ItemVO: ICloneable
      {
        public ItemVO()
        {
            ItemId = ""; 
            ItemCategory = ""; 
        }
    
        public string ItemId { get; set; }
        public string ItemCategory { get; set; }
    
        public object Clone()
        {
            return new ItemVO
            {
                ItemId = this.ItemId,
                ItemCategory = this.ItemCategory
            }; 
        }
     }
    

    Now notice that you need an explicit cast when using Clone() (or you can make your own that returns ItemVO).

    duplicateItemVO = (ItemVO) originalItemVO.Clone(); 
    
    0 讨论(0)
  • 2020-12-08 14:33

    You cannot practically copy an object since they would more likely be of reference types. The ideal method is to serialize or stream the object into a new one - Provided your class is serializable (by providing the [Serializable] attribute in class declaration).

    private static T Clone<T>(T source)
        {
            if (!typeof(T).IsSerializable)
            {
                throw new ArgumentException("The type must be serializable.", "source");
            }
    
            if (Object.ReferenceEquals(source, null))
            {
                return default(T);
            }
    
            System.Runtime.Serialization.IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
            Stream stream = new MemoryStream();
            using (stream)
            {
                formatter.Serialize(stream, source);
                stream.Seek(0, SeekOrigin.Begin);
                return (T)formatter.Deserialize(stream);
            }
        }
    

    Now you can use this code:

    [Serializable]
    public class MyClass
    {
      public int a {get; set;}
      public int b {get; set;}
    }     
    
    var obj = new MyClass{
    a = 10,
    b = 20,
    };
    
    var newobj = Clone<MyClass>(obj);
    

    You will get an entirely new copy of obj. Note: Any other class inside MyClass must also be declared with the attribute [Serializable].

    0 讨论(0)
  • 2020-12-08 14:35

    You would need to construct a new instance of your class, not just assign the variable:

    duplicateItemVO = new ItemVO 
        { 
            ItemId = originalItemVO.ItemId, 
            ItemCategory = originalItemVO.ItemCategory 
        };
    

    When you're dealing with reference types (any class), just assigning a variable is creating a copy of the reference to the original object. As such, setting property values within that object will change the original as well. In order to prevent this, you need to actually construct a new object instance.

    0 讨论(0)
  • 2020-12-08 14:37

    class are reference type and when you change one instance it will change the ariginal refference. so use value type object for overcome your task(ex: use struct instead of class)

    public struct ItemVO { *** }
    

    or you can implement ICloneable Interface for your class

    0 讨论(0)
提交回复
热议问题