ReadonlyCollection, are the objects immutable?

后端 未结 3 1036
隐瞒了意图╮
隐瞒了意图╮ 2021-01-19 01:44

I\'m trying using ReadOnlyCollection to make object immutable, I want the property of object are immutable.

public ReadOnlyCollection MyRea         


        
3条回答
  •  执念已碎
    2021-01-19 02:07

    I tried to change the property of the object in to MyReadOnlyList using a foreach and ... I can change value property, is it correct? I understood ReadOnlyCollection set an add level to make the object immutable.

    Using a ReadOnlyCollection does not make any guarantees as for the object that is stored in the collection. All it guarantees is that the collection cannot be modified once it has been created. If an element is retrieved from it, and it has mutable properties, it can very well be modified.

    If you want to make your FooObject an immutable one, then simply do so:

    public class FooObject
    {
        public FooObject(string someString, int someInt)
        {
            SomeString = someString;
            SomeInt = someInt;
        }
    
        public string SomeString { get; };
        public int SomeInt { get; };
    }
    

提交回复
热议问题