Indexers in List vs Array

前端 未结 6 2022
误落风尘
误落风尘 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 05:06

    List has a normal indexer which behaves like a property. The access goes through accessor functions, and those are by-value.

    T this[int index]
    {
        get{return arr[index];}
        set{arr[index]=value;}}
    }
    

    Arrays are special types, and their indexer is field-like. Both the runtime and the C# compiler have special knowledge of arrays, and that enables this behavior. You can't have the array like behavior on custom types.

    Fortunately this is rarely a problem in practice. Since you only use mutable structs in rare special cases(high performance or native interop), and in those you usually prefer arrays anyways due to their low overhead.


    You get the same behavior with properties vs. fields. You get a kind of reference when using a field, but a copy when you use a property. Thus you can write to members of value-type fields, but not members of value-type properties.

提交回复
热议问题