简体   繁体   English

具有两个不同对象的参考的奇怪问题

[英]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.

相关问题 随机选择两个不同的对象会导致对象引用相同的值 - Random Selection of two different objects causes objects to reference same value 对象的反序列化有问题 - Having a problem with deserialization of an objects 参考和对象克隆的奇怪问题 - Strange problem with reference and object cloning 在调试时确定两个对象在不同范围内的引用相等性 - Determine reference equality of two objects in different scopes while debugging 为什么相同类型的两个不同对象的gettype具有相同的引用 - Why gettype for two different objects of same type has same reference 如何最好地从2个不同的DLL中填充几乎相同类的2个不同的对象,而不必维护两个不同的对象? - How to best populate 2 different objects, of an almost identical class, from 2 different DLLs without having to maintain two different objects? 引用类中的不同种类的对象 - Reference different kind of objects in a class 应该.GetHashCode()为内存中具有不同refences的两个对象返回相同的值吗? - Should .GetHashCode() return same value for two objects having different refences in the memory? 两个具有常见布尔问题的If语句 - Two If statements having a common bool problem Code First两个具有其他对象的对象 - Code First two objects having other object
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM