Can't change struct's members value inside generic collections

前端 未结 3 1946
灰色年华
灰色年华 2020-12-06 18:25

Imagine this struct :

        struct Person
        {
             public string FirstName { get; set; }
             public string LastName { g         


        
3条回答
  •  生来不讨喜
    2020-12-06 19:07

    When you return the struct via the List[] indexer, it returns a copy of the entry. So if you assigned the FirstName there, it would just be thrown away. Hence the compiler error.

    Either rewrite your Person to be a reference type class, or do a full reassignment:

    Person person = list[1];
    person.FirstName = "F22";
    list[1] = person;
    

    Generally speaking, mutable structs bring about issues such as these that can cause headaches down the road. Unless you have a really good reason to be using them, you should strongly consider changing your Person type.

    Why are mutable structs “evil”?

提交回复
热议问题