“Read only” Property Accessor in C#

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

    Use a ReadOnlyCollection.

    return new ReadOnlyCollection(mMyList).

    You can also make the ReadOnlyCollection a field, and it will automatically reflect changes in the underlying list. This is the most efficient solution.

    If you know that mMyList only contains one type of object (eg, it has nothing but DateTimes), you can return a ReadOnlyCollection (or some other type) for additional type safety. If you're using C# 3, you can simply write

    return new ReadOnlyCollection(mMyList.OfType().ToArray())

    However, this will not automatically update with the underlying list, and is also less efficient (It will copy the entire list). The best option is to make mMyList a generic List (eg, a List)

    提交回复
    热议问题