How to make a reference type property “readonly”

后端 未结 8 683
青春惊慌失措
青春惊慌失措 2020-12-28 20:23

I have a class Bar with a private field containing the reference type Foo. I would like to expose Foo in a public property, but I do n

8条回答
  •  轮回少年
    2020-12-28 20:33

    It sounds like you're after the equivalent of "const" from C++. This doesn't exist in C#. There's no way of indicating that consumers can't modify the properties of an object, but something else can (assuming the mutating members are public, of course).

    You could return a clone of the Foo as suggested, or possibly a view onto the Foo, as ReadOnlyCollection does for collections. Of course if you could make Foo an immutable type, that would make life simpler...

    Note that there's a big difference between making the field readonly and making the object itself immutable.

    Currently, the type itself could change things in both ways. It could do:

    _Foo = new Foo(...);
    

    or

    _Foo.SomeProperty = newValue;
    

    If it only needs to be able to do the second, the field could be readonly but you still have the problem of people fetching the property being able to mutate the object. If it only needs to do the first, and actually Foo is either already immutable or could be made immutable, you can just provide a property which only has the "getter" and you'll be fine.

    It's very important that you understand the difference between changing the value of the field (to make it refer to a different instance) and changing the contents of the object that the field refers to.

提交回复
热议问题