I have a struct which I put in a List<T>
, I want to edit some value in that struct at a specific position. Is this at all possible without making a copy of the struct, editing the copy, and replacing the entry in the List?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
From J.Richter's "CLR via C#", 3rd edition:
...
Consider this code:
and it's usage:
The output is:
So it does what you need.
However the same won't work for
List<T>
. I guess by the reason, mentioned by Alexei Levenkov. So, I would strongly recommend you to changestruct
toclass
if the type in question is not immutable per instance.Your best bet is probably to have your structures expose their fields directly, and then use code like:
I consider the failure of .net to provide any means of updating list items in place to be a significant weakness in .net, but would still consider an exposed-field struct as being far superior to any alternative in cases where one wishes to represent a small group of orthogonal values which should not be "attached" to any other such group (such as the coordinates in a point, the origin and size of a rectangle, etc.) The notion that structs should be "immutable" has been repeated as mantra for a long time, but that doesn't mean it's good advice. Such notion stems largely from two things:
In reality, if a type is supposed to represent a small group of orthogonal values, an exposed-field struct is a perfect fit. Even if one has to use clunky code like that shown above to update a field of an item in a
List<structType>
, it's better than any alternative using class types or so-called "immutable" structs. Knowing thatmyList
is a structure with an exposed fieldX
would be enough to completely understand the code above. The only remotely decent alternative if one were using a class or "immutable" struct would bemyList[3] = myList[3].WithX(myList[3].X + 4);
, but that would require that the type in question to offer aWithX
method (and presumably aWithWhatever()
method for each field). Such methods would increase many fold the amount of code one would have to read to find out for certain what a method would actually do (one might expect thatWithX
would return a new instance which was identical to the old one except for the value ofX
, but one wouldn't know until one read all the code involved; by contrast, knowing thatX
is an exposed field of the structure type would be sufficient to know what the above code would do.No, to be able to do it you need reference to element of inner array which is not provided by
List
/IList
.You can do that with unsafe code and arrays if you have to.