在列表VS数组索引 [英] Indexers in List vs Array
问题描述
如何在索引器在列表和数组定义
How are the Indexers are defined in List and Arrays.
列表<&MYSTRUCT GT;名单=新名单,LT; MYSTRUCT>();
,其中 MYSTRUCT
是一个结构。现在考虑
MYSTRUCT [] ARR =新MYSTRUCT [10];
List<MyStruct> lists=new List<MyStruct>();
where MyStruct
is a Structure. Now Consider
MyStruct[] arr=new MyStruct[10];
常用3 [0]
对所述第一结构的引用item.But 列表[0]
给我的一个副本。
是有它为什么是这样做的任何原因。
此外,由于的Int32
是结构列表<&的Int32 GT; list1的=新的List<的Int32>();
怎样可以让我访问 list1的[0]
或分配 list1的[0] = 5
其中,因为它是不可能做列表[0] ._ x = 5
arr[0]
gives a reference to the first Structure item.But lists[0]
gives me a copy of it.
Is there any reason why it is done like that.
Also since Int32
is structure List<Int32> list1 =new List<Int32>();
how it is possible for me to access list1[0]
or assign list1[0]=5
where as it is not possible to do lists[0]._x=5
推荐答案
虽然它们看起来是一样的,数组索引和列表索引正在做完全不同的事情。
Although they look the same, the array indexer and list indexer are doing completely separate things.
在列表< T>
索引器的声明与参数的属性:
The List<T>
indexer is declared as a property with a parameter:
public T this[int index] { get; set; }
这被编译到 get_Item
和被称为喜欢当参数被访问的任何其他方法set_Item
方法。
数组索引器内的直接支持CLR;有获取的托管指针数组的第n个元素特定的IL指令 ldelema
(负载元件地址)。该指针然后可以通过任何的一个指针指向直接改变该地址的东西其他IL指令使用。
The array indexer has direct support within the CLR; there is a specific IL instruction ldelema
(load element address) for getting a managed pointer to the n'th element of an array. This pointer can then be used by any of the other IL instructions that take a pointer to directly alter the thing at that address.
例如, stfld
(存储域值)指令可以采取托管指针指定这个实例来存储在现场,也可以使用指针直接调用数组中的事情的方法。
For example, the stfld
(store field value) instruction can take a managed pointer specifying the 'this' instance to store the field in, or you can use the pointer to call methods directly on the thing in the array.
在C#中的说法,数组索引器返回的变量的,但列表索引器返回的值的
In C# parlance, the array indexer returns a variable, but the list indexer returns a value.
这篇关于在列表VS数组索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!