[英]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, 当我将
kref
分配给其他对象之后,
KurumReferans kRefIstakip = new KurumReferans();
kRefIstakip = kRef;
kRefIstakip.Referans = "SORUMLU";
tempReferans
object's values change but I want to old values. tempReferans
对象的值更改,但我想使用旧值。
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] 编辑:您已标记该类具有[Serializable]属性
In the line: 在该行中:
kRefIstakip = kRef;
the object kRef
is also referenced by kRefIstakip
. kRef
还引用对象kRefIstakip
。 Because you are assigning kRef
instance to kRefIstakip
, not copying kRef
to kRefIstakip
. 因为您是将
kRef
实例分配给kRefIstakip
,而不是将kRef
复制到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
. 不会将
obj2
的值复制到obj1
,但是会将obj2
引用复制到obj1
。 And then both can access same memory location. 然后两者都可以访问相同的内存位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.