Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
CSharp_Prog_Guide.doc
Скачиваний:
16
Добавлен:
16.11.2019
Размер:
6.22 Mб
Скачать

Компиляция кода

Для выполнения этого кода скопируйте класс в проект консольного приложения на языке Visual C#, которое было создано в среде разработки Visual Studio. По умолчанию этот проект предназначен для версии 3.5 платформы .NET Framework и имеет ссылку на библиотеку System.Core.dll и директиву для пространства имен System.Linq. Если одно или более требований в проекте отсутствуют, их можно добавить вручную.

Fields

This topic describes fields, which are objects or values in a class or struct. Fields enable classes and structures to encapsulate data.

For simplicity, these examples use fields that are public, but we do not recommend this practice. Fields should generally be private. External classes should access fields indirectly through methods, properties, or indexers.

Fields

Fields store the data a class must have to fulfill its design. For example, a class that represents a calendar date might have three integer fields: one for the month, one for the day, and one for the year. Fields are declared in the class block by specifying the access level of the field, followed by the type of the field, followed by the name of the field. For example:

public class CalendarDate

{

public int month;

public int day;

public int year;

}

To access a field in an object, add a period after the object name, followed by the name of the field, as in objectname.fieldname. For example:

CalendarDate birthday = new CalendarDate();

birthday.month = 7;

Поля

В этом разделе описываются поля, являющиеся объектами или значениями в классах или структурах. Поля позволяют классам и структурам инкапсулировать данные.

Для простоты в этих примерах используются открытые поля, но на практике это не рекомендуется. Лучше использовать закрытые поля. Внешние классы должны получать доступ к полям опосредованно, с помощью методов, свойств или индексаторов.

Поля

В полях хранятся данные, необходимые классу для выполнения своей функции. Например, в классе, представляющем календарную дату, может быть три целочисленных поля: одно для месяца, одно для числа, одно для года. Поля объявляются в блоке класса путем указания уровня доступа поля, за которым следует тип поля и имя поля. Пример.

public class CalendarDate

{

public int month;

public int day;

public int year;

}

Для доступа к члену объекта нужно добавить точку после имени объекта и указать имя поля: objectname.fieldname. Пример.

CalendarDate birthday = new CalendarDate();

birthday.month = 7;

A field can be given an initial value by using the assignment operator when the field is declared. To automatically assign the month field to 7, for example, you would declare month as in the following example:

public class CalendarDateWithInitialization

{

public int month = 7;

//...

}

Fields are initialized immediately before the constructor for the object instance is called. If the constructor assigns the value of a field, it will overwrite any value given during field declaration.

Note:

A field initializer cannot refer to other instance fields.

Fields can be marked as public, private, protected, internal, or protected internal. These access modifiers define how users of the class can access the fields.

A field can optionally be declared static. This makes the field available to callers at any time, even if no instance of the class exists.

A field can be declared readonly. A read-only field can only be assigned a value during initialization or in a constructor. A staticreadonly field is very similar to a constant, except that the C# compiler does not have access to the value of a static read-only field at compile time, only at run time.

Полю можно назначить первоначальное значение, используя оператор присвоения при объявлении поля. Например, чтобы автоматически присвоить полю month значение 7, можно объявить поле month как указано в следующем примере:

public class CalendarDateWithInitialization

{

public int month = 7;

//...

}

Поля инициализируются непосредственно перед вызовом конструктора для экземпляра объекта. Если конструктор присваивает полю значение, оно заменит значения, присвоенные при объявлении поля.

Примечание.

Инициализатор поля не может ссылаться на другие поля экземпляров.

Поля могут быть отмечены модификаторами public, private, protected, internal или protected internal. Эти модификаторы доступа определяют порядок доступа к полю для пользователей класса.

Также при необходимости поле может быть объявлено с модификатором static. При этом поле становится доступным для вызова в любое время, даже если экземпляр класса отсутствует.

Также при необходимости поле может быть объявлено с модификатором readonly. Полю с этим модификатором (то есть полю, доступному только для чтения) значения могут быть присвоены только при инициализации или в конструкторе. Поле с модификаторами static readonly (статическое, доступное только для чтения) очень похоже на константу, за исключением того, что компилятор C# не имеет доступа к значению такого поля при компиляции: доступ возможен только во время выполнения.

Constants

Classes and structs can declare constants as members. Constants are values which are known at compile time and do not change. (To create a constant value that is initialized at runtime, use the readonly keyword.) Constants are declared as a field by using the const keyword before the type of the field. C# does not support const methods, properties, or events.

Constants must be initialized as they are declared. For example:

class Calendar1

{

public const int months = 12;

}

In this example, the constant months will always be 12, and it cannot be changed even by the class itself. Constants must have a type of sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, or string), an enumeration, or a reference to null.

Multiple constants of the same type can be declared at the same time, for example:

class Calendar2

{

const int months = 12, weeks = 52, days = 365;

}

The expression that is used to initialize a constant can refer to another constant as long as it does not create a circular reference. For example:

class Calendar3

{

const int months = 12;

const int weeks = 52;

const int days = 365;

const double daysPerWeek = days / weeks;

const double daysPerMonth = days / months;

}

Constants can be marked as public, private, protected, internal, or protectedinternal. These access modifiers define how users of the class can access the constant.

Constants are accessed as if they were static fields, although they cannot use the static keyword. Expressions that are not in the class that defines the constant must use the class name, a period, and the name of the constant to access the constant. For example:

int birthstones = Calendar.months;