“Read only” Property Accessor in C#

前端 未结 8 1597
遇见更好的自我
遇见更好的自我 2021-02-12 14:08

I have the following class:

class SampleClass
{
   private ArrayList mMyList;

   SampleClass()
   {
       // Initialize mMyList
   }

   public ArrayList MyLis         


        
8条回答
  •  南方客
    南方客 (楼主)
    2021-02-12 15:09

    Use the ArrayList.ReadOnly() method to construct and return a read-only wrapper around the list. it won't copy the list, but simply make a read-only wrapper around it. In order to get compile-time checking, you probably want to return the read-only wrapper as IEnumerable as @Jared suggests.

    public IEnumerable MyList
    {
         get { return ArrayList.ReadOnly(mMyList); }
    }
    

    A collection that is read-only is simply a collection with a wrapper that prevents modifying the collection. If changes are made to the underlying collection, the read-only collection reflects those changes.

    This method is an O(1) operation.

    Reference

提交回复
热议问题