简体   繁体   中英

c# by reference or by value

Let's say I have a list of objects and that I'm extracting and modifying an item from the list like this:

List<MyObject> TheListOfObjects = new List<MyObject>();
MyObject TheObject = new MyObject();

TheListOfObjects = //some json deserialization result

TheObject = (from o in TheListOfObject
             where o.ID == SomeParameter
             select o).SingleOrDefault();

TheObject.SomeProperty = SomeValue;

When I write TheObject.SomeProperty = SomeValue; am I:

  1. modifying the item in the list and in which case I'm done or
  2. modifying a new item and I must replace the original item in the list with the item I just modified.

Depends.

If the list of objects is a list of class instances, then TheObject variable will hold a value that is a reference . This reference will also still exist within the list. Modifications of the object at that reference will be visible in both. Important caveat: Writing over the reference contained in the variable (ie., variable reassignment) would not persist to the list, nor would writing over the reference in the list persist to the variable.

If the list of objects is a list of struct instances, then TheObject simply contains the value , and mutations of that value are not visible inside the list.

That depends on whether the MyObject is a class or a struct.

If it's a class, you're modifying the original object.
If it's a struct, you're modifying a copy.

You are modifying the item in the list as the call returns a reference to the item in the list, not a copy of it. Also, the object you create with

MyObject TheObject = new MyObject();

is just thrown away, as you change the reference to the newly selected item. You could omit that line and just do:

MyObject theObject = (from o in TheListOfObject
         where o.ID == SomeParameter
         select o).SingleOrDefault();

I assume that MyObject is a class, and not a struct, because we are mutating it with the operation, and mutable structs are evil

列表中的项目仅供参考,因此您正在修改同一对象-无需尝试将其复制回列表中,因为它已经存在。

You are modifying an item in the list . TheObject is a reference to an unique item in memory.

You can even create multiple lists, all lists will contain references to identical objects in memory.


There is something wrong with your code:

MyObject TheObject = new MyObject();

...

TheObject = (from o in TheListOfObject
             where o.ID == SomeParameter
             select o).SingleOrDefault();

You are first creating a new instance of the object, the affecting to TheObject a new value.

The = new MyObject(); part of your code is useless. Same for = new List<MyObject>();

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