“Read only” Property Accessor in C#

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

    With an ArrayList you are fairly limited because there is no readonly non-generic collection class in the BCL. The quick and dirty solution is to return a type of IEnumerable.

       public IEnumerable MyList
       {
           get { return mMyList;}
       }
    

    This won't actually prevent someone from casting to ArrayList but it won't allow edits by default either

    You can return an effectively readonly list by calling ArrayList.ReadOnly. However it's return type is an ArrayList so the user would still be able to compile with .Add but it would produce a runtime error.

提交回复
热议问题