gpt4 book ai didi

c# - 什么是数组索引?

转载 作者:太空狗 更新时间:2023-10-30 00:13:58 24 4
gpt4 key购买 nike

我知道List<T>例如,索引器类似于属性。摘自msdn:

Indexers allow instances of a class or struct to be indexed just like arrays. Indexers resemble properties except that their accessors take parameters.

但我不明白为什么会发生以下情况:

int[] myArray = new int[0];
List<int> myList = new List<int>();

Interlocked.Increment(ref myArray[0]); // fine

Interlocked.Increment(ref myList[0]); //CS0206 A property or indexer may not be passed as an out or ref parameter

他们不应该以同样的方式工作吗?

最佳答案

List<T> 的索引器允许您使用属性(方法)访问元素,这使它看起来像一个数组。您不能通过 ref 传递生成的方法就好像你写道:

Interlocked.Increment(ref myList.GetItem.get_Item(0));

但是访问数组的元素不是通过索引器。 CLR 直接支持访问数组元素。所以array[i]返回一个可以通过 ref 传递的变量.

来自 C# 规范:

Even though the syntax for accessing an indexer element is the same as that for an array element, an indexer element is not classified as a variable. Thus, it is not possible to pass an indexer element as a ref or out argument.

这是 List<T> 的索引器(内部使用数组):

public T this[int index]
{
get
{ // some checks removed
return _items[index];
}

set { _items[index] = value;}
}

从 IL 端:

访问数组元素会生成这条直接 IL 指令:

IL_0014: ldelem.i4

通过索引器访问 List 的元素会生成:

IL_001b:  callvirt   instance !0 class [mscorlib]System.Collections.Generic.List`1<int32>::get_Item(int32)

因此,它是相同的 C# 语法。但是生成的IL是完全不同的。

关于c# - 什么是数组索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38147936/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com