List<T>和Array之间按值和按引用的区别,用于自定义结构和内置结构(如Int32)

问题描述 投票:0回答:1

我知道使用列表和数组索引器之间有一个小但重要的区别。 Array 返回成员的引用,而 List 复制成员值。我无法理解的是,这条规则非常适合自定义结构,但不适用于像 Int32 这样的内置结构。

List<int> numbers;

List<Mutable> mutablesList; 
Mutable[] mutablesArray;

public struct Mutable
{
    public int X;
}

numbers[0]++; // OK
mutablesArray[0].X++; //OK
mutablesList[0].X++ //Compiler error

不幸的是,我在这个问题上找不到任何合理的解释。

c# arrays list struct indexer
1个回答
0
投票

表达式

list[x]++
将被解释为:

a = list.get_Item(x)
a = a + 1
list.set_Item(x, a)

同样,

list[x].y++
将被解释为:

a = list.get_Item(x)
b = a.y + 1
c = list.get_Item(x)
c.y = b

从上面的伪代码可以看出,finally

list[x]
并没有改变。因此,编译器会阻止这个无意义的操作。

© www.soinside.com 2019 - 2024. All rights reserved.