I have List<T>, and I do the following:
List<T>
var myObj = List[2]; //Return object at position 2 myObj.Name = "fred"; //If you look at List[2] its name has changed to fred
I tried the following, but it still updates the item in the list
var newObj = new MyObj(); var myObj = List[2]; //Return object at position 2 newObj = myObj; newObj.Name = "fred"; //If you look at List[2] its name has still changed to fred
How can I avoid this pointer so that I can update properties without updating it in the list?
Great comments, thanks, but this is what I implemented:
public MyObj Clone() { BinaryFormatter bFormatter = new BinaryFormatter(); MemoryStream stream = new MemoryStream(); bFormatter.Serialize(stream, this); stream.Seek(0, SeekOrigin.Begin); MyObj newObj = (MyObj)bFormatter.Deserialize(stream); return newObj; }
You can create an ICloneable with MemberwiseClone , and then:
var myObj = List[2]; var newObj = myObj.Clone(); newObj.Name = "fred";
UPDATE:
, ICloneable, , . Clone .
ICloneable
Clone
- , . :
MyObj a = new MyObj(); MyObj b = a; a.Name = "Test"; Console.WriteLine(b.Name); // Will print "Test"
- ( , ), .
.
, , . -, .
? , , ?
var newObj = new MyObj(List[2]); newObj.Name = "fred";
, , . , , -
var newObj = new MyObj(List[2],"fred");
- , .
, , -, " " ( IClonable ), , , newObj? ? ? , /, ?
. # " ", , , ( "" ) . , , . , , . , , . , ICloneable, , "" . , , - " ". , ? " " . , " !"
Source: https://habr.com/ru/post/1728275/More articles:Область локальной переменной функции Python во время исключений - scopeWCF Answer Too Long - Authentication Failed - asp.netОтказоустойчивость для длинных сценариев python - pythonhow to know that java socket is dead - javaSynchronizing branches of synchronization - mergeHow to check if Java ResourceBundle is loaded without loading it? - javaПочему Visual С++ 2010 жалуется на "Использование неинициализированной памяти"? - c++Question Microsoft Accelerator V2 - toArray2D - f #Встроенная сборка внутри петель - c++Tracking Open Source Users on iPhone - iphoneAll Articles