When C# uses list, it prompts that the return value of List<T>.this[int] cannot be modified because it is not a variable

namespace WindowsFormsApplication1
{
    
    
    public class Pt3DClass
    {
    
    
        public int x;
        public int y;
        public int z;
        public Pt3DClass(int ix = 0, int iy = 0, int iz = 0)
        {
    
    
            x = ix;
            y = iy;
            z = iz;
        }
    }
    public struct Pt3DStruct
    {
    
    
        public int x;
        public int y;
        public int z;
        public Pt3DStruct(int ix = 0, int iy = 0, int iz = 0)
        {
    
    
            x = ix;
            y = iy;
            z = iz;
        }
    }
    public partial class Form1 : Form
    {
    
    
        public Form1()
        {
    
    
            Pt3DClass ptc = new Pt3DClass(1,2,3);
            List<Pt3DClass> lstc = new List<Pt3DClass>();
            lstc.Add(ptc);
            lstc[0].x = 999;

            Pt3DStruct pts = new Pt3DStruct(4,5,6);
            List<Pt3DStruct> lsts = new List<Pt3DStruct>();
            lsts.Add(pts);
            lsts[0].x = 666;

            InitializeComponent();
        }
    }
}

When writing the above code in VS, as shown below, an error will be reported: the return value of List.this[int] cannot be modified because it is not a variable.
Insert picture description here
Looking carefully at the above code, we can find that the List storing the class can directly assign values ​​to the objects in the elements, but the List storing the structures cannot directly assign values ​​to the objects in the elements.
Reason:
list[i] inherits the method
object this[ in IList int index] {get; set;}
Used in List. When obtaining an object, if the element in the List is a struct, then it is actually a value transfer; if it is a class, it transfers the address of the object. By value transfer, it returns a temporary copy and cannot change its value, so it will report an error

Guess you like

Origin blog.csdn.net/weixin_43935474/article/details/105738157
Recommended