C# Solution to Error Reporting for Value Field Assignment in List<structure>

1. Error analysis

	//定义结构体
    public struct MyStruct
    {
        public float a;
        public float b;
    }
	//报错场景复现
	void Main()
    {
        List<MyStruct> list = new List<MyStruct>();
        list.Add(new MyStruct());
        list[0].a = 5;  //这句编译器会报错
    }
  • The above list[0].a = 5; will report an error. The error is as follows
    : indexer access return temporary value.cannot modify struct member when acces
    This is because list[0] returns a copy of the object, not a reference to the object.
    When running list[0].a = 5, it actually modifies the value type of the copy, and cannot modify the value in the actual reference as we expected. This is meaningless, so the compiler throws an error.

Two, the solution

1: Modify the temporary copy, and finally assign it back

  • This is the most practical method. We first use list[i] to get a copy and modify the copy. Finally, set it back, such as the following code
        //先拿到副本
        MyStruct myStruct = list[0];
        //做一些赋值操作
        myStruct.a = 5;
        ...
        
        //最后再设置回来
        list[0] = myStruct;

2: Modify the structure into a class

  • Modify the structure into a class, and there will not be so many things. But this is not very good, because since the structure is used in the design, there must be your reason, and it is not good to change it back because of this problem.

3: Encapsulate the value field of the structure in the reference field

    //把a封装在类里
    public class MyClass
    {
        public int a;
    }
    
    public struct MyStruct
    {
        public MyClass myClass;
        public float b;
    }
     
     void Main()
    {
        List<MyStruct> list = new List<MyStruct>();
        list.Add(new MyStruct());
        list[0].myClass.a = 5;
    }

It can be changed to this, but it is still too troublesome. It is recommended to use the first method.

3. Official reference documents

Finally, attach the official reference documents, interested friends can look at
the compiler error CS1612

Guess you like

Origin blog.csdn.net/aaa27987/article/details/123158144