Заглавная страница Избранные статьи Случайная статья Познавательные статьи Новые добавления Обратная связь FAQ Написать работу КАТЕГОРИИ: АрхеологияБиология Генетика География Информатика История Логика Маркетинг Математика Менеджмент Механика Педагогика Религия Социология Технологии Физика Философия Финансы Химия Экология ТОП 10 на сайте Приготовление дезинфицирующих растворов различной концентрацииТехника нижней прямой подачи мяча. Франко-прусская война (причины и последствия) Организация работы процедурного кабинета Смысловое и механическое запоминание, их место и роль в усвоении знаний Коммуникативные барьеры и пути их преодоления Обработка изделий медицинского назначения многократного применения Образцы текста публицистического стиля Четыре типа изменения баланса Задачи с ответами для Всероссийской олимпиады по праву Мы поможем в написании ваших работ! ЗНАЕТЕ ЛИ ВЫ?
Влияние общества на человека
Приготовление дезинфицирующих растворов различной концентрации Практические работы по географии для 6 класса Организация работы процедурного кабинета Изменения в неживой природе осенью Уборка процедурного кабинета Сольфеджио. Все правила по сольфеджио Балочные системы. Определение реакций опор и моментов защемления |
Arrays and the generic IList interfaceСодержание книги
Поиск на нашем сайте
A one-dimensional array T[] implements the interface System.Collections.Generic.IList<T> (IList<T> for short) and its base interfaces. Accordingly, there is an implicit conversion from T[] to IList<T> and its base interfaces. In addition, if there is an implicit reference conversion from S to T then S[] implements IList<T> and there is an implicit reference conversion from S[] to IList<T> and its base interfaces (§6.1.6). If there is an explicit reference conversion from S to T then there is an explicit reference conversion from S[] to IList<T> and its base interfaces (§6.2.4). For example: using System.Collections.Generic; class Test IList<string> lst1 = sa; // Ok IList<string> lst5 = (IList<string>)oa1; // Exception The assignment lst2 = oa1 generates a compile-time error since the conversion from object[] to IList<string> is an explicit conversion, not implicit. The cast (IList<string>)oa1 will cause an exception to be thrown at run-time since oa1 references an object[] and not a string[]. However the cast (IList<string>)oa2 will not cause an exception to be thrown since oa2 references a string[]. Whenever there is an implicit or explicit reference conversion from S[] to IList<T>, there is also an explicit reference conversion from IList<T> and its base interfaces to S[] (§6.2.4). When an array type S[] implements IList<T>, some of the members of the implemented interface may throw exceptions. The precise behavior of the implementation of the interface is beyond the scope of this specification. Array creation Array instances are created by array-creation-expressions (§7.6.10.4) or by field or local variable declarations that include an array-initializer (§12.6). When an array instance is created, the rank and length of each dimension are established and then remain constant for the entire lifetime of the instance. In other words, it is not possible to change the rank of an existing array instance, nor is it possible to resize its dimensions. An array instance is always of an array type. The System.Array type is an abstract type that cannot be instantiated. Elements of arrays created by array-creation-expressions are always initialized to their default value (§5.2). Array element access Array elements are accessed using element-access expressions (§7.6.6.1) of the form A[I1, I2,..., IN], where A is an expression of an array type and each IX is an expression of type int, uint, long, ulong, or can be implicitly converted to one or more of these types. The result of an array element access is a variable, namely the array element selected by the indices. The elements of an array can be enumerated using a foreach statement (§8.8.4). Array members Every array type inherits the members declared by the System.Array type. Array covariance For any two reference-types A and B, if an implicit reference conversion (§6.1.6) or explicit reference conversion (§6.2.4) exists from A to B, then the same reference conversion also exists from the array type A[R] to the array type B[R], where R is any given rank-specifier (but the same for both array types). This relationship is known as array covariance. Array covariance in particular means that a value of an array type A[R] may actually be a reference to an instance of an array type B[R], provided an implicit reference conversion exists from B to A. Because of array covariance, assignments to elements of reference type arrays include a run-time check which ensures that the value being assigned to the array element is actually of a permitted type (§7.17.1). For example: class Test static void Main() { The assignment to array[i] in the Fill method implicitly includes a run-time check which ensures that the object referenced by value is either null or an instance that is compatible with the actual element type of array. In Main, the first two invocations of Fill succeed, but the third invocation causes a System.ArrayTypeMismatchException to be thrown upon executing the first assignment to array[i]. The exception occurs because a boxed int cannot be stored in a string array. Array covariance specifically does not extend to arrays of value-types. For example, no conversion exists that permits an int[] to be treated as an object[]. Array initializers Array initializers may be specified in field declarations (§10.5), local variable declarations (§8.5.1), and array creation expressions (§7.6.10.4): array-initializer: variable-initializer-list: variable-initializer: An array initializer consists of a sequence of variable initializers, enclosed by “{”and “}” tokens and separated by “,” tokens. Each variable initializer is an expression or, in the case of a multi-dimensional array, a nested array initializer. The context in which an array initializer is used determines the type of the array being initialized. In an array creation expression, the array type immediately precedes the initializer, or is inferred from the expressions in the array initializer. In a field or variable declaration, the array type is the type of the field or variable being declared. When an array initializer is used in a field or variable declaration, such as: int[] a = {0, 2, 4, 6, 8}; it is simply shorthand for an equivalent array creation expression: int[] a = new int[] {0, 2, 4, 6, 8}; For a single-dimensional array, the array initializer must consist of a sequence of expressions that are assignment compatible with the element type of the array. The expressions initialize array elements in increasing order, starting with the element at index zero. The number of expressions in the array initializer determines the length of the array instance being created. For example, the array initializer above creates an int[] instance of length 5 and then initializes the instance with the following values: a[0] = 0; a[1] = 2; a[2] = 4; a[3] = 6; a[4] = 8; For a multi-dimensional array, the array initializer must have as many levels of nesting as there are dimensions in the array. The outermost nesting level corresponds to the leftmost dimension and the innermost nesting level corresponds to the rightmost dimension. The length of each dimension of the array is determined by the number of elements at the corresponding nesting level in the array initializer. For each nested array initializer, the number of elements must be the same as the other array initializers at the same level. The example: int[,] b = {{0, 1}, {2, 3}, {4, 5}, {6, 7}, {8, 9}}; creates a two-dimensional array with a length of five for the leftmost dimension and a length of two for the rightmost dimension: int[,] b = new int[5, 2]; and then initializes the array instance with the following values: b[0, 0] = 0; b[0, 1] = 1; If a dimension other than the rightmost is given with length zero, the subsequent dimensions are assumed to also have length zero. The example: int[,] c = {}; creates a two-dimensional array with a length of zero for both the leftmost and the rightmost dimension: int[,] c = new int[0, 0]; When an array creation expression includes both explicit dimension lengths and an array initializer, the lengths must be constant expressions and the number of elements at each nesting level must match the corresponding dimension length. Here are some examples: int i = 3; Here, the initializer for y results in a compile-time error because the dimension length expression is not a constant, and the initializer for z results in a compile-time error because the length and the number of elements in the initializer do not agree. Interfaces An interface defines a contract. A class or struct that implements an interface must adhere to its contract. An interface may inherit from multiple base interfaces, and a class or struct may implement multiple interfaces. Interfaces can contain methods, properties, events, and indexers. The interface itself does not provide implementations for the members that it defines. The interface merely specifies the members that must be supplied by classes or structs that implement the interface. Interface declarations An interface-declaration is a type-declaration (§9.6) that declares a new interface type. interface-declaration: An interface-declaration consists of an optional set of attributes (§17), followed by an optional set of interface-modifiers (§13.1.1), followed by an optional partial modifier, followed by the keyword interface and an identifier that names the interface, followed by an optional variant- type-parameter-list specification (§13.1.3), followed by an optional interface-base specification (§13.1.4), followed by an optional type-parameter-constraints-clauses specification (§10.1.5), followed by an interface-body (§13.1.5), optionally followed by a semicolon. Interface modifiers An interface-declaration may optionally include a sequence of interface modifiers: interface-modifiers: interface-modifier: It is a compile-time error for the same modifier to appear multiple times in an interface declaration. The new modifier is only permitted on interfaces defined within a class. It specifies that the interface hides an inherited member by the same name, as described in §10.3.4. The public, protected, internal, and private modifiers control the accessibility of the interface. Depending on the context in which the interface declaration occurs, only some of these modifiers may be permitted (§3.5.1). Partial modifier The partial modifier indicates that this interface-declaration is a partial type declaration. Multiple partial interface declarations with the same name within an enclosing namespace or type declaration combine to form one interface declaration, following the rules specified in §10.2.
|
||||
Последнее изменение этой страницы: 2016-08-10; просмотров: 263; Нарушение авторского права страницы; Мы поможем в написании вашей работы! infopedia.su Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав. Обратная связь - 3.12.36.65 (0.008 с.) |