“Read only” Property Accessor in C#

前端 未结 8 1602
遇见更好的自我
遇见更好的自我 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:03

    You should wrap the return value in a read only collection.

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题