Название: Professional C# 6 and .NET Core 1.0
Автор: Christian Nagel
Издательство: John Wiley & Sons Limited
Жанр: Зарубежная образовательная литература
isbn: 9781119096634
isbn:
Color is defined as an enum type and contains a few colors. The enum types are explained in detail later in the section Enums (code file StaticConstructorSample/Enum.cs):
The Main method just invokes the WriteLine method and writes the user preferences back color to the console (code file StaticConstructorSample/Program.cs):
Compiling and running the preceding code results in the following output:
Of course, if the code is executed during the weekend, your color preference would be Green.
Readonly Members
If you do not want to change a data member after initialization, the readonly keyword can be used. Let’s get into the details of readonly fields and readonly properties.
Readonly Fields
To guarantee that fields of an object cannot be changed, fields can be declared with the readonly modifier. Fields with the readonly modifier can be assigned only values from constructors. This is different from the const modifier. With the const modifier, the compiler replaces the variable by its value everywhere it is used. The compiler already knows the value of the constant. Read-only fields are assigned during runtime from a constructor. Contrary to const fields, read-only fields can be instance members. For using a read-only field as a class member, the static modifier needs to be assigned to the field.
Suppose that you have a program that edits documents, and for licensing reasons you want to restrict the number of documents that can be opened simultaneously. Assume also that you are selling different versions of the software, and it’s possible for customers to upgrade their licenses to open more documents simultaneously. Clearly, this means you can’t hard-code the maximum number in the source code. You would probably need a field to represent this maximum number. This field has to be read in – perhaps from a registry key or some other file storage – each time the program is launched. Therefore, your code might look something like this:
In this case, the field is static because the maximum number of documents needs to be stored only once per running instance of the program. This is why it is initialized in the static constructor. If you had an instance readonly field, you would initialize it in the instance constructor(s). For example, presumably each document you edit has a creation date, which you wouldn’t want to allow the user to change (because that would be rewriting the past!).
As noted earlier, date is represented by the class System.DateTime. The following code initializes the _creationTime field in the constructor using the DateTime struct. After initialization of the Document class, the creation time cannot be changed anymore:
CreationDate and MaxDocuments in the previous code snippet are treated like any other field, except that because they are read-only they cannot be assigned outside the constructors:
It’s also worth noting that you don’t have to assign a value to a readonly field in a constructor. If you don’t do so, it is left with the default value for its particular data type or whatever value you initialized it to at its declaration. That applies to both static and instance readonly fields.
Readonly Properties
It is possible to create a read-only property by simply omitting the set accessor from the property definition. Thus, to make Name a read-only property, you would do the following:
Конец ознакомительного фрагмента.
Текст предоставлен ООО «ЛитРес».
Прочитайте эту книгу целиком, купив полную легальную версию на ЛитРес.
Безопасно оплатить книгу можно банковской картой Visa, MasterCard, Maestro, со счета мобильного телефона, с платежного терминала, в салоне МТС или Связной, через PayPal, WebMoney, Яндекс.Деньги, QIWI Кошелек, бонусными картами или другим удобным Вам способом.