开发者

Object still linked (referenced) after selecting it out of list?

I was wondering, and i'm not really sure, but help me out here.

If you have a List items, and there's one object you need to change a property of it. Say myClass has a string property "status". I'm searching my list with a for-loop and i get my object so i do

myClass item = items[i];

if i want to change the "status" property, i do this for example :

item.S开发者_如何转开发tatus = "new status";

My question/issue is this: is "item" still linked to the list item, so that if i execute the line above, it will be changed in the list as well without having to set this :

items[i] = item;

Hope this is clear.

Thanks in advance.


Both the list and the item variable have references to the actual object. Any changes you make to the object are visible through either reference.

To put it another way... suppose you look through the phone book, and pick a particular address. You copy the address onto a piece of paper, and then drive there. You then paint the house red. Now anyone else who looks up the same address in the phone book and goes there will still see a red house, even though they haven't seen your piece of paper.

Have a look at my article about value types and reference types for a bit more information.

(This is all assuming that myClass really is a class, by the way.)


Yes, you are altering the item that is in the list. You do not need to assign it to the list again.


Yes, if myClass is a class as the name suggests (and not a struct) it is a reference type. Therefore it is not copied when you write myClass item = items[i];. item is merely a reference to the same object that items[i] references.


The code item.Status = "new status"; will change the list item

items[i] points to a myClass object.

When you say myClass item = items[i];, it is referenced by both item and items[i].

so when you alter one of the properties like this item.Status = "new status"; you're actually making changes to your myClass object which now has two names item and items[i].

You can also use item[i].Status = "new status";. Both do the same job.

Setting items[i] = item; has no effect, since both reference the same object already.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜