Best practice: How to expose a read-only ICollection

前端 未结 7 1579
礼貌的吻别
礼貌的吻别 2020-12-16 02:39

I have an ICollection called foos in my class which I want to expose as read-only (see this question). I see that the interface defines a

7条回答
  •  时光说笑
    2020-12-16 03:05

    You can make "foos" a ReadOnlyCollection like this:

    ReadOnlyCollection readOnlyCollection = foos.ToList().AsReadOnly();
    

    Then you can expose it as a property of your class.

    EDIT:

        class FooContainer
        {
            private ICollection foos;
            public ReadOnlyCollection ReadOnlyFoos { get { return foos.ToList().AsReadOnly();} }
    
        }
    

    Note: You should remember that once you get the ReadOnlyFoos collection is no longer "synchronized" with your foos ICollection. See the thread you referenced.

提交回复
热议问题