[英]Strange problem with two different objects having reference
When a ClaimDetail is added to tmpClaim, this ClaimDetail is also added to claim. 将ClaimDetail添加到tmpClaim时,也会将该ClaimDetail添加到Claim。 Can someone explain me why this occurs?
有人可以解释一下为什么会这样吗?
List<Claim> claims; // list data
foreach ( Claim claim in claims) {
Claim tmpClaim = datacontext.Claims.FirstOrDefault ( c => c.Id == claim.Id );
ClaimDetail claimDetail = new ClaimDetail ( );
claimDetail.ClaimDetailType = "Type";
// add claim
datacontext.Claims.InsertOnSubmit ( tmpClaim );
datacontext.SubmitChanges ( );
}
tmpClaim
isn't a new object. tmpClaim
不是一个新对象。 It's still a reference back to an element within claims
. 它仍然是对
claims
元素的引用。
What this essentially means is that whatever you do to tmpClaim
is also happening with claims
. 从本质
tmpClaim
,这意味着您对tmpClaim
任何事情也在发生claims
。 They are the same thing. 他们是一样的东西。
If you don't want changes to tmpClaim
to affect claims
, you'll need to create a new Claim
(as well as any copying/cloning that is necessary) and do all of your work on that new object. 如果您不希望对
tmpClaim
进行更改以影响claims
,则需要创建一个new Claim
(以及必要的任何复制/克隆操作)并在该新对象上进行所有工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.