How to make a reference type property “readonly”

后端 未结 8 679
青春惊慌失措
青春惊慌失措 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:32

    "Cloning" the Foo objects you receive and give back out is a normal practice called defensive copying. Unless there is some unseen side-effect to cloning that will be visible to the user, there is absolutely no reason to NOT do this. It is often the only way to protect your classes' internal private data, especially in C# or Java, where the C++ idea of const is not available. (IE, it must be done in order to properly create truly immutable objects in these two languages.)

    Just to clarify, possible side effects would be things like your user (reasonably) expecting that the original object be returned, or some resource being held by Foo that will not be cloned correctly. (In which case, what is it doing implementing IClonable?!)

提交回复
热议问题