How to make IEnumerable readonly?

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

    In fact, IEnumerable is already readonly. It means you cannot replace any items in the underlying collection with different items. That is, you cannot alter the references to the Person objects that are held in the collection. The type Person is not read only, however, and since it's a reference type (i.e. a class), you can alter its members through the reference.

    There are two solutions:

    • Use a struct as the return type (that makes a copy of the value each time it's returned, so the original value will not be altered — which can be costly, by the way)
    • Use read only properties on the Person type to accomplish this task.

提交回复
热议问题