Indexers in List vs Array

前端 未结 6 2011
误落风尘
误落风尘 2020-12-10 04:30

How are the Indexers are defined in List and Arrays.

List lists=new List(); where MyStruct is a Structure.

6条回答
  •  既然无缘
    2020-12-10 04:56

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

    The List 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.

提交回复
热议问题