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

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

The typeof operator






The typeofoperator is used to obtain the System.Typeobject for a type.

typeof-expression:
typeof (type)
typeof (unbound-type-name)
typeof (void)

unbound-type-name:
identifier generic-dimension-specifieropt
identifier:: identifier generic-dimension-specifieropt
unbound-type-name. identifier generic-dimension-specifieropt

generic-dimension-specifier:
< commasopt >

commas:
,
commas,

The first form of typeof-expression consists of a typeof keyword followed by a parenthesized type. The result of an expression of this form is the System.Type object for the indicated type. There is only one System.Type object for any given type. This means that for a type T, typeof(T) == typeof(T) is always true. The type cannot be dynamic.

The second form of typeof-expression consists of a typeof keyword followed by a parenthesized unbound-type-name. An unbound-type-name is very similar to a type-name (§3.8) except that an unbound-type-name contains generic-dimension-specifiers where a type-name contains type-argument-lists. When the operand of a typeof-expression is a sequence of tokens that satisfies the grammars of both unbound-type-name and type-name, namely when it contains neither a generic-dimension-specifier nor a type-argument-list, the sequence of tokens is considered to be a type-name. The meaning of an unbound-type-name is determined as follows:

· Convert the sequence of tokens to a type-name by replacing each generic-dimension-specifier with a type-argument-list having the same number of commas and the keyword object as each type-argument.

· Evaluate the resulting type-name, while ignoring all type parameter constraints.

· The unbound-type-name resolves to the unbound generic type associated with the resulting constructed type (§4.4.3).

The result of the typeof-expression is the System.Type object for the resulting unbound generic type.

The third form of typeof-expression consists of a typeof keyword followed by a parenthesized void keyword. The result of an expression of this form is the System.Type object that represents the absence of a type. The type object returned by typeof(void) is distinct from the type object returned for any type. This special type object is useful in class libraries that allow reflection onto methods in the language, where those methods wish to have a way to represent the return type of any method, including void methods, with an instance of System.Type.

The typeof operator can be used on a type parameter. The result is the System.Type object for the run-time type that was bound to the type parameter. The typeof operator can also be used on a constructed type or an unbound generic type (§4.4.3). The System.Type object for an unbound generic type is not the same as the System.Type object of the instance type. The instance type is always a closed constructed type at run-time so its System.Type object depends on the run-time type arguments in use, while the unbound generic type has no type arguments.

The example

using System;

class X<T>
{
public static void PrintTypes() {
Type[] t = {
typeof(int),
typeof(System.Int32),
typeof(string),
typeof(double[]),
typeof(void),
typeof(T),
typeof(X<T>),
typeof(X<X<T>>),
typeof(X<>)
};
for (int i = 0; i < t.Length; i++) {
Console.WriteLine(t[i]);
}
}
}

class Test
{
static void Main() {
X<int>.PrintTypes();
}
}

produces the following output:

System.Int32
System.Int32
System.String
System.Double[]
System.Void
System.Int32
X`1[System.Int32]
X`1[X`1[System.Int32]]
X`1[T]

Note that int and System.Int32 are the same type.

Also note that the result of typeof(X<>) does not depend on the type argument but the result of typeof(X<T>) does.







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



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

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

Композиция из абстрактных геометрических фигур Данная композиция состоит из линий, штриховки, абстрактных геометрических форм...

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

Типы конфликтных личностей (Дж. Скотт) Дж. Г. Скотт опирается на типологию Р. М. Брансом, но дополняет её. Они убеждены в своей абсолютной правоте и хотят, чтобы...

Гносеологический оптимизм, скептицизм, агностицизм.разновидности агностицизма Позицию Агностицизм защищает и критический реализм. Один из главных представителей этого направления...

Функциональные обязанности медсестры отделения реанимации · Медсестра отделения реанимации обязана осуществлять лечебно-профилактический и гигиенический уход за пациентами...

Разновидности сальников для насосов и правильный уход за ними   Сальники, используемые в насосном оборудовании, служат для герметизации пространства образованного кожухом и рабочим валом, выходящим через корпус наружу...

Дренирование желчных протоков Показаниями к дренированию желчных протоков являются декомпрессия на фоне внутрипротоковой гипертензии, интраоперационная холангиография, контроль за динамикой восстановления пассажа желчи в 12-перстную кишку...

Деятельность сестер милосердия общин Красного Креста ярко проявилась в период Тритоны – интервалы, в которых содержится три тона. К тритонам относятся увеличенная кварта (ув.4) и уменьшенная квинта (ум.5). Их можно построить на ступенях натурального и гармонического мажора и минора.  ...

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