How to Clone Objects

后端 未结 13 1238
北海茫月
北海茫月 2020-11-30 04:36

When I do the following.. anything done to Person b modifies Person a (I thought doing this would clone Person b from Person a). I also have NO idea if changing Person a wil

13条回答
  •  温柔的废话
    2020-11-30 04:58

      public static T Clone(T obj)
      {
          DataContractSerializer dcSer = new  DataContractSerializer(obj.GetType());
          MemoryStream memoryStream = new MemoryStream();
    
          dcSer.WriteObject(memoryStream, obj);
          memoryStream.Position = 0;
    
          T newObject = (T)dcSer.ReadObject(memoryStream);
          return newObject;
      }
    

提交回复
热议问题