Get struct item by index in list and array

前端 未结 2 1632
一向
一向 2021-01-02 15:54

When I use an array of structs (for example System.Drawing.Point), I can get item by index and change it.

For example (This code work fine):

<         


        
2条回答
  •  旧时难觅i
    2021-01-02 16:48

    The reason is that structs are value types so when you access a list element you will in fact access an intermediate copy of the element which has been returned by the indexer of the list.

    Other words, when using the List, you're are creating copies.

    MSDN

    Error Message

    Cannot modify the return value of 'expression' because it is not a variable

    An attempt was made to modify a value type that was the result of an intermediate expression. Because the value is not persisted, the value will be unchanged.

    To resolve this error, store the result of the expression in an intermediate value, or use a reference type for the intermediate expression.

    Solution:

    List points = new List  { new Point(0,0), new Point(1,1), new Point(2,2) };
    for (int i = 0; i < points.Count; i++)
    {
        Point p = points[i];
        p.X += 1;
        //and don't forget update the old value, because we're using copy
        points[i] = p;
    }
    

提交回复
热议问题