简体   繁体   中英

Private class data design pattern is silly?

I'm reading this page

I am confused as to what is wrong with the first example. Why cannot he just add readonly to the declaration of the private fields?

The keyword readonly (or its equivalent) is provided in some languages (for example, C# and VB.NET ) but not others.

C++ is an example of an object-oriented language that does not have a keyword stipulating "This can be set at any part of a constructor function, but nowhere else".

Object oriented design patterns are meant to be language neutral: applying to all object-oriented languages. It follows from this that some languages might have extra features which make a particular pattern obsolete.

In this instance, the presentation of the pattern appears extra silly because the pattern is introduced, then the example is provided in C# which doesn't need it.

He very well could use readonly . It sounds like he doesn't understand what readonly does. From MSDN :

The readonly keyword is a modifier that you can use on fields. When a field declaration includes a readonly modifier, assignments to the fields introduced by the declaration can only occur as part of the declaration or in a constructor in the same class.

You can set readonly fields in a constructor. In fact, you would have to -- how else are those fields going to have any meaningful value?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM