“Read only” Property Accessor in C#

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

    Just to expand on JaredPar's answer. As he said, returning the actual backing field is not completely safe, since the user is still able to dynamically cast the IEnumerable back to an ArrayList.

    I would write something like this to be sure no modifications to the original list are made:

    public IEnumerable MyList
    {
        get
        {
             foreach (object o in mMyList)
                 yield return o;
        }
    }
    

    Then again, I would probabily also use a generic list (IEnumerable) to be completely type safe.

提交回复
热议问题