Kri*_*hna 5 c# reference pass-by-reference
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!
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);
Run Code Online (Sandbox Code Playgroud)
Please use that approach for value holder types only, especially not for types that implement IDisposable or something similar.
小智 5
我找到了一种使用AutoMapper的方法。虽然AutoMapper看起来像一个很棒的工具,但是我无法在需要Net2.0 / Mono的项目中使用它。
您可以使用序列化程序来创建对象的副本/克隆。我使用json.NET是因为我已经在项目中使用它了,但是我想其他库也可以使用。基本上,您将对象序列化为一个字符串,然后从该字符串创建一个新对象,因为该字符串未绑定到原始对象,所以您将获得一个全新的对象。
这是使用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);
Run Code Online (Sandbox Code Playgroud)
您甚至可以将最后三行缩短为以下形式:
list1.Add(JsonConvert.DeserializeObject<SomeObject>(JsonConvert.SerializeObject(obj1)));
Run Code Online (Sandbox Code Playgroud)
您可能可以编写一个函数/方法来为您执行此操作。由于我创建自己的对象类型,因此向该对象添加了一个对象,如下所示:
public ItemInputData copyOf()
{
string data = JsonConvert.SerializeObject(this);
ItemInputData copy = JsonConvert.DeserializeObject<ItemInputData>(data);
return copy;
}
Run Code Online (Sandbox Code Playgroud)
用于将副本添加到列表的代码如下所示:
list1.Add(item.copyOf());
Run Code Online (Sandbox Code Playgroud)
希望这会帮助=]