How to Clone Objects

后端 未结 13 1264
北海茫月
北海茫月 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 05:07

    It couldn't be simpler than this:

        public SomeClass Clone () {
    
            var clonedJson = JsonConvert.SerializeObject (this);
    
            return JsonConvert.DeserializeObject (clonedJson);
        }
    

    Just serialize any object to a JSON string and then deserialize it. This will do a deep copy...

提交回复
热议问题