The readonly keyword in C # indicates that fields in the class can only be initialized during definition or in the constructor. Normal data can achieve the expected results, but in the object or list, to achieve the read-only effect, only one readonly keyword is not allowed. When you modify a list with readonly, you can still use the add and remove methods in other classes to change it. However, the read-only attribute you want may be:Only items in this list can be modified in the current class!
The following example shows a list modified with the readonly keyword. Its content items can still be added or deleted in other classes:
Even if it is encapsulated as a read-only attribute, you can still operate in other classes:
However, you can change the attribute type to ienumerable <t> to achieve the desired effect. Because the ienumerable <t> class does not have the add and remove methods, the list <t> class inherits the ienumerable <t> class, And the add and remove methods added to the List <t> class are as follows:
If you want to create a fully read-only attribute, you can use readonlycollection even if it cannot be modified in the current class. <t>:
In. Net 4.5, list <t> inherits ireadonlylist <t> and ireadonlycollection <t>, giving us a simpler way of writing, which can also achieve the above results: