Adding a clone of an object to a list in c# (prevent modification from outside)

∥☆過路亽.° 提交于 2019-12-23 11:53:41

问题


I have an object like 'obj1' which I want to add to a list. I can add it by just list1.add(obj1) .Now once I update obj1, the object in my list is also updating! (I understand that I am dealing with references here)

My requirement demands modifying the obj1 and add it to the list again! Instead of having two different objects, I have only one, because for both of them, the reference is the same - obj1.

Is there any way I can modify this obj1 and add it to the list and still not lose the old one? Any workarounds would be extremely helpful!

Thanks in Advance!


回答1:


The C# language does not support cloning of objects. Therefore, if obj1 is not a value object (i.e. a struct), you cannot do that. Note: there is the possibility of implementing ICloneable, however, its use is not advised.

One approach I use in another project is to use AutoMapper to create a copy of the object before inserting into the list. Example:

MyType copy = Mapper.DynamicMap(obj1);
list.Add(copy);

Please use that approach for value holder types only, especially not for types that implement IDisposable or something similar.




回答2:


I found a way to do it with out AutoMapper. While AutoMapper looks like a great tool, I was unable to use it in my project which requires Net2.0/Mono.

You can use a serializer to create a copy/clone of an object. I used json.NET since I was using it already in my project, but I imagine other libraries would work as well. Basically, you serialize the object into a string, and then create a new object from that string, since the string isn't tied to the original object, you get a completely new object.

Here is an example of code using json.net:

List<SomeObject> list1 = new List<SomeObject>();
SomeObject obj1 = new SomeObject(params, etc);

string data = JsonConvert.SerializeObject(obj1);
SomeObject obj2 = JsonConvert.DeserializeObject<SomeObject>(data);
list1.Add(obj2);

You could even shorten the last three lines down to something like this:

list1.Add(JsonConvert.DeserializeObject<SomeObject>(JsonConvert.SerializeObject(obj1)));

You could probably write a function/method to do this for you. Since I was making my own object types, I added one to the object which looked like this:

public ItemInputData copyOf()
{
    string data = JsonConvert.SerializeObject(this);
    ItemInputData copy = JsonConvert.DeserializeObject<ItemInputData>(data);
    return copy;
}

And the code for adding a copy to the list looked like this:

list1.Add(item.copyOf());

Hope this helps =]



来源:https://stackoverflow.com/questions/22526136/adding-a-clone-of-an-object-to-a-list-in-c-sharp-prevent-modification-from-outs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!