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

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

Variant type parameter lists






Variant type parameter lists can only occur on interface and delegate types. The difference from ordinary type-parameter-lists is the optional variance-annotation on each type parameter.

variant-type-parameter-list:
< variant-type-parameters >

variant-type-parameters:
attributesopt variance-annotationopt type-parameter
variant-type-parameters, attributesopt variance-annotationopt type-parameter

variance-annotation:
in
out

If the variance annotation is out, the type parameter is said to be covariant. If the variance annotation is in, the type parameter is said to be contravariant. If there is no variance annotation, the type parameter is said to be invariant.

In the example

interface C<out X, in Y, Z>
{
X M(Y y);

Z P { get; set; }
}

X is covariant, Y is contravariant and Z is invariant.

13.1.3.1 Variance safety

The occurrence of variance annotations in the type parameter list of a type restricts the places where types can occur within the type declaration.

A type T is output-unsafe if one of the following holds:

· T is a contravariant type parameter

· T is an array type with an output-unsafe element type

· T is an interface or delegate type S<A1,… AK> constructed from a generic type S<X1,.. XK> where for at least one Ai one of the following holds:

o Xi is covariant or invariant and Ai is output-unsafe.

o Xi is contravariant or invariant and Ai is input-safe.

A type T is input-unsafe if one of the following holds:

· T is a covariant type parameter

· T is an array type with an input-unsafe element type

· T is an interface or delegate type S<A1,… AK> constructed from a generic type S<X1,.. XK> where for at least one Ai one of the following holds:

o Xi is covariant or invariant and Ai is input-unsafe.

o Xi is contravariant or invariant and Ai is output-unsafe.

Intuitively, an output-unsafe type is prohibited in an output position, and an input-unsafe type is prohibited in an input position.

A type is output-safe if it is not output-unsafe, and input-safe if it is not input-unsafe.

13.1.3.2 Variance conversion

The purpose of variance annotations is to provide for more lenient (but still type safe) conversions to interface and delegate types. To this end the definitions of implicit (§6.1) and explicit conversions (§6.2) make use of the notion of variance-convertibility, which is defined as follows:

A type T<A1, …, An> is variance-convertible to a type T<B1, …, Bn> if T is either an interface or a delegate type declared with the variant type parameters T<X1, …, Xn>, and for each variant type parameter Xi one of the following holds:

· Xi is covariant and an implicit reference or identity conversion exists from Ai to Bi

· Xi is contravariant and an implicit reference or identity conversion exists from Bi to Ai

· Xi is invariant and an identity conversion exists from Ai to Bi







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



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

ТЕОРЕТИЧЕСКАЯ МЕХАНИКА Статика является частью теоретической механики, изучающей условия, при ко­торых тело находится под действием заданной системы сил...

Теория усилителей. Схема Основная масса современных аналоговых и аналого-цифровых электронных устройств выполняется на специализированных микросхемах...

Логические цифровые микросхемы Более сложные элементы цифровой схемотехники (триггеры, мультиплексоры, декодеры и т.д.) не имеют...

Обзор компонентов Multisim Компоненты – это основа любой схемы, это все элементы, из которых она состоит...

Кран машиниста усл. № 394 – назначение и устройство Кран машиниста условный номер 394 предназначен для управления тормозами поезда...

Приложение Г: Особенности заполнение справки формы ву-45   После выполнения полного опробования тормозов, а так же после сокращенного, если предварительно на станции было произведено полное опробование тормозов состава от стационарной установки с автоматической регистрацией параметров или без...

Значення творчості Г.Сковороди для розвитку української культури Важливий внесок в історію всієї духовної культури українського народу та її барокової літературно-філософської традиції зробив, зокрема, Григорій Савич Сковорода (1722—1794 pp...

Постинъекционные осложнения, оказать необходимую помощь пациенту I.ОСЛОЖНЕНИЕ: Инфильтрат (уплотнение). II.ПРИЗНАКИ ОСЛОЖНЕНИЯ: Уплотнение...

Приготовление дезинфицирующего рабочего раствора хлорамина Задача: рассчитать необходимое количество порошка хлорамина для приготовления 5-ти литров 3% раствора...

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