Студопедия — Constants
Студопедия Главная Случайная страница Обратная связь

Разделы: Автомобили Астрономия Биология География Дом и сад Другие языки Другое Информатика История Культура Литература Логика Математика Медицина Металлургия Механика Образование Охрана труда Педагогика Политика Право Психология Религия Риторика Социология Спорт Строительство Технология Туризм Физика Философия Финансы Химия Черчение Экология Экономика Электроника

Constants






A constant is a class member that represents a constant value: a value that can be computed at compile-time. A constant-declaration introduces one or more constants of a given type.

constant-declaration:
attributesopt constant-modifiersopt const type constant-declarators;

constant-modifiers:
constant-modifier
constant-modifiers constant-modifier

constant-modifier:
new
public
protected
internal
private

constant-declarators:
constant-declarator
constant-declarators, constant-declarator

constant-declarator:
identifier = constant-expression

A constant-declaration may include a set of attributes (§17), a new modifier (§10.3.4), and a valid combination of the four access modifiers (§10.3.5). The attributes and modifiers apply to all of the members declared by the constant-declaration. Even though constants are considered static members, a constant-declaration neither requires nor allows a static modifier. It is an error for the same modifier to appear multiple times in a constant declaration.

The type of a constant-declaration specifies the type of the members introduced by the declaration. The type is followed by a list of constant-declarators, each of which introduces a new member. A constant-declarator consists of an identifier that names the member, followed by an “=” token, followed by a constant-expression (§7.19) that gives the value of the member.

The type specified in a constant declaration must be sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, string, an enum-type, or a reference-type. Each constant-expression must yield a value of the target type or of a type that can be converted to the target type by an implicit conversion (§6.1).

The type of a constant must be at least as accessible as the constant itself (§3.5.4).

The value of a constant is obtained in an expression using a simple-name (§7.6.2) or a member-access (§7.6.4).

A constant can itself participate in a constant-expression. Thus, a constant may be used in any construct that requires a constant-expression. Examples of such constructs include case labels, goto case statements, enum member declarations, attributes, and other constant declarations.

As described in §7.19, a constant-expression is an expression that can be fully evaluated at compile-time. Since the only way to create a non-null value of a reference-type other than string is to apply the new operator, and since the new operator is not permitted in a constant-expression, the only possible value for constants of reference-types other than string is null.

When a symbolic name for a constant value is desired, but when the type of that value is not permitted in a constant declaration, or when the value cannot be computed at compile-time by a constant-expression, a readonly field (§10.5.2) may be used instead.

A constant declaration that declares multiple constants is equivalent to multiple declarations of single constants with the same attributes, modifiers, and type. For example

class A
{
public const double X = 1.0, Y = 2.0, Z = 3.0;
}

is equivalent to

class A
{
public const double X = 1.0;
public const double Y = 2.0;
public const double Z = 3.0;
}

Constants are permitted to depend on other constants within the same program as long as the dependencies are not of a circular nature. The compiler automatically arranges to evaluate the constant declarations in the appropriate order. In the example

class A
{
public const int X = B.Z + 1;
public const int Y = 10;
}

class B
{
public const int Z = A.Y + 1;
}

the compiler first evaluates A.Y, then evaluates B.Z, and finally evaluates A.X, producing the values 10, 11, and 12. Constant declarations may depend on constants from other programs, but such dependencies are only possible in one direction. Referring to the example above, if A and B were declared in separate programs, it would be possible for A.X to depend on B.Z, but B.Z could then not simultaneously depend on A.Y.

Fields

A field is a member that represents a variable associated with an object or class. A field-declaration introduces one or more fields of a given type.

field-declaration:
attributesopt field-modifiersopt type variable-declarators;

field-modifiers:
field-modifier
field-modifiers field-modifier

field-modifier:
new
public
protected
internal
private
static
readonly
volatile

variable-declarators:
variable-declarator
variable-declarators, variable-declarator

variable-declarator:
identifier
identifier = variable-initializer

variable-initializer:
expression
array-initializer

A field-declaration may include a set of attributes (§17), a new modifier (§10.3.4), a valid combination of the four access modifiers (§10.3.5), and a static modifier (§10.5.1). In addition, a field-declaration may include a readonly modifier (§10.5.2) or a volatile modifier (§10.5.3) but not both. The attributes and modifiers apply to all of the members declared by the field-declaration. It is an error for the same modifier to appear multiple times in a field declaration.

The type of a field-declaration specifies the type of the members introduced by the declaration. The type is followed by a list of variable-declarators, each of which introduces a new member. A variable-declarator consists of an identifier that names that member, optionally followed by an “=” token and a variable-initializer (§10.5.5) that gives the initial value of that member.

The type of a field must be at least as accessible as the field itself (§3.5.4).

The value of a field is obtained in an expression using a simple-name (§7.6.2) or a member-access (§7.6.4). The value of a non-readonly field is modified using an assignment (§7.17). The value of a non-readonly field can be both obtained and modified using postfix increment and decrement operators (§7.6.9) and prefix increment and decrement operators (§7.7.5).

A field declaration that declares multiple fields is equivalent to multiple declarations of single fields with the same attributes, modifiers, and type. For example

class A
{
public static int X = 1, Y, Z = 100;
}

is equivalent to

class A
{
public static int X = 1;
public static int Y;
public static int Z = 100;
}







Дата добавления: 2015-09-07; просмотров: 449. Нарушение авторских прав; Мы поможем в написании вашей работы!



Картограммы и картодиаграммы Картограммы и картодиаграммы применяются для изображения географической характеристики изучаемых явлений...

Практические расчеты на срез и смятие При изучении темы обратите внимание на основные расчетные предпосылки и условности расчета...

Функция спроса населения на данный товар Функция спроса населения на данный товар: Qd=7-Р. Функция предложения: Qs= -5+2Р,где...

Аальтернативная стоимость. Кривая производственных возможностей В экономике Буридании есть 100 ед. труда с производительностью 4 м ткани или 2 кг мяса...

Гидравлический расчёт трубопроводов Пример 3.4. Вентиляционная труба d=0,1м (100 мм) имеет длину l=100 м. Определить давление, которое должен развивать вентилятор, если расход воздуха, подаваемый по трубе, . Давление на выходе . Местных сопротивлений по пути не имеется. Температура...

Огоньки» в основной период В основной период смены могут проводиться три вида «огоньков»: «огонек-анализ», тематический «огонек» и «конфликтный» огонек...

Упражнение Джеффа. Это список вопросов или утверждений, отвечая на которые участник может раскрыть свой внутренний мир перед другими участниками и узнать о других участниках больше...

Классификация холодных блюд и закусок. Урок №2 Тема: Холодные блюда и закуски. Значение холодных блюд и закусок. Классификация холодных блюд и закусок. Кулинарная обработка продуктов...

ТЕРМОДИНАМИКА БИОЛОГИЧЕСКИХ СИСТЕМ. 1. Особенности термодинамического метода изучения биологических систем. Основные понятия термодинамики. Термодинамикой называется раздел физики...

Травматическая окклюзия и ее клинические признаки При пародонтите и парадонтозе резистентность тканей пародонта падает...

Studopedia.info - Студопедия - 2014-2024 год . (0.007 сек.) русская версия | украинская версия