List<> of struct with property. Cannot change value of property. why?

这个返回如下错误:"Cannot modify the return value of 'System.Collections.Generic.List<MyStruct>.this[int]' because it is not a variable"

class Program
{
    private struct MyStruct
    {
        private int myVar;
        public int MyProperty
        {
            get { return myVar; }
            set { myVar = value; }
        }
    }

    private static List<MyStructlist> list = new List<MyStruct>();

    private static void Main(string[] args)
    {
        MyStruct x = new MyStruct();
        x.MyProperty = 45;
        list.Add(x);
        list[0].MyProperty = 45; // <----------- ERROR HERE
    }
}

The [] operator on a list is, in fact, a function, so the value stored at that location in the list is returned as a function result,on the stack.

This doesn't cause problems for reference types, because usually you want to change some property of the reference type, so the fact that you get a copy of the reference in the list (not the actual reference that is in the list) doesn't cause problems.

However, for value types exactly the same thing happens, and it does cause problems: the value is copied from the list onto the stack and returned as a function result. Modifying the returned value, of course, has no effect on the contents of the list. The compiler wisely catches this.

//You need to do this:

MyStruct y = list[0]; y.MyProperty = 45; list[0] = y;
原文地址:https://www.cnblogs.com/ring1992/p/6385105.html