Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
324 views
in Technique[技术] by (71.8m points)

c# - Indexers in List vs Array

How are the Indexers are defined in List and Arrays.

List<MyStruct> lists=new List<MyStruct>(); where MyStruct is a Structure. Now Consider MyStruct[] arr=new MyStruct[10];

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Although they look the same, the array indexer and list indexer are doing completely separate things.

The List<T> indexer is declared as a property with a parameter:

public T this[int index] { get; set; }

This gets compiled to get_Item and set_Item methods that are called like any other method when the parameter is accessed.

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.

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.

In C# parlance, the array indexer returns a variable, but the list indexer returns a value.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...