Get a reference to a struct inside array

后端 未结 4 1559
执笔经年
执笔经年 2020-12-07 21:38

I want to modify a field of a struct which is inside an array without having to set entire struct. In the example below, I want to set one field of element 543 in the array.

4条回答
  •  南方客
    南方客 (楼主)
    2020-12-07 22:00

    While Jon Skeet is correct about why your program doesn't compile, you can just do:

    s[543].a = 3;
    

    ...and it will operate directly on the struct in the array rather than on a copy.

    Note that this idea works for arrays only, other collections such as lists will return a copy out from the indexer-getter (giving you a compiler error if you try something similar on the resulting value).

    On another note, mutable structs are considered evil. Is there a strong reason why you don't want to make S a class?

提交回复
热议问题