How to make IEnumerable readonly?

前端 未结 8 798
臣服心动
臣服心动 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

    They aren't pointing to the same .Net collection, but rather, to the same Person objects. The line:

    List p = new List(list1Instance.Get()); 
    

    copies all the Person elements from list1Instance.Get() to list p. The word "copies" here means copies the references. So, your list and IEnumerable just happen to point to the same Person objects.

    IEnumerable is always readonly, by definition. However, the objects inside may be mutable, as in this case.

提交回复
热议问题