How to make IEnumerable readonly?

前端 未结 8 653
臣服心动
臣服心动 2021-02-07 12:23

Why are the lists list1Instance and p in the Main method of the below code pointing to the same collection?

class Person
         


        
相关标签:
8条回答
  • 2021-02-07 13:06

    If your person object is a real object then you should consider using an immutable version.

     public class Person
     {
         public FirstName {get; private set;}
         public LastName {get; private set;}
         public Person(firstName, lastName)
         {
             FirstName = firstName;
             LastName = lastName;
         }
      }
    

    In this way its not possible to change the content of the instance once created and therefore it isn't important that existing instances are reused in multiple lists.

    0 讨论(0)
  • 2021-02-07 13:08

    Return a new instance of Person that is a copy of p instead of p itself in Get(). You'll need a method to make a deep-copy of a Person object to do this. This won't make them read only, but they will be different than those in the original list.

    public IEnumerable<Person> Get()
    {
        foreach (Person p in l1)
        {
            yield return p.Clone();
        }
    }
    
    0 讨论(0)
提交回复
热议问题