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

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

Imagine this struct :

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


        
3条回答
  •  时光说笑
    2020-12-06 18:49

    Redo your struct as such:

        struct Person
        {
             private readonly string firstName;
             private readonly string lastName;
             public Person(string firstName, string lastName)
             {
                 this.firstName = firstName;
                 this.lastName = lastName;
             }
             public string FirstName { get { return this.firstName; } }
             public string LastName { get { return this.lastName; } }
        }
    

    And following code as :

        var list = new List();
        list.Add(new Person("F1", "L1"));
        list.Add(new Person("F2", "L2"));
        list.Add(new Person("F3", "L3"));
    
        // Can modify the expression because it's a new instance
        list[1] = new Person("F22", list[1].LastName);
    

    This is due to the copy semantics of struct. Make it immutable and work within those constraints and the problem goes away.

提交回复
热议问题