简体   繁体   中英

Object change in C#

When I write this code I see an unexpected situation how can I solve this?

KurumReferans tempReferans = new KurumReferans();
tempReferans = kRef; 

if (kurumDetaylari.IsTakipMekanizmasiKullaniyor == true)
{
    KurumReferans kRefIstakip = new KurumReferans();
    kRefIstakip = kRef;
    kRefIstakip.Referans = "SORUMLU";
    kRefIstakip.Yontem = "SORUMLU:";
    kRefIstakip.Tipi = Tipi.Zorunlu;
    kRefIstakip.Parent = kurum;
    PostAddEdit(db.KurumReferans, kRefIstakip, cmd, "", "", "", "");
}

Firstly I assign,

tempReferans = kRef;

After when I assign kref to other object,

KurumReferans kRefIstakip = new KurumReferans();
kRefIstakip = kRef;
kRefIstakip.Referans = "SORUMLU";

tempReferans object's values change but I want to old values.

Your object is getting changed, because when you assign an object, it just assigns the address to it and both variable uses same memory space or object. To overcome this, you have to make a deep copy of the object and assign.

public static T DeepClone<T>(T obj)
{
 using (var ms = new MemoryStream())
 {
   var formatter = new BinaryFormatter();
   formatter.Serialize(ms, obj);
   ms.Position = 0;

   return (T) formatter.Deserialize(ms);
 }
}

EDIT: You have mark that class with attribute [Serializable]

In the line:

kRefIstakip = kRef;

the object kRef is also referenced by kRefIstakip . Because you are assigning kRef instance to kRefIstakip , not copying kRef to kRefIstakip .

In Reference Type objects, the code:

obj1 = obj2;

doesn't copy the values of obj2 to obj1 , but it copies obj2 reference to obj1 . And then both can access same memory location.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM