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

Оператор ??

Оператор ?? определяет значение по умолчанию, возвращаемое при присвоении допускающего значение null типа не допускающему значение null типу.

int? c = null;

// d = c, unless c is null, in which case d = -1.

int d = c ?? -1;

Этот оператор может также использоваться с несколькими допускающими значение null типами. Например:

int? e = null;

int? f = null;

// g = e or f, unless e and f are both null, in which case g = -1.

int g = e ?? f ?? -1;

Тип bool?

Допускающий значение null тип bool? может содержать три значения: true, false и null.

Допускающие значение null логические типы аналогичны логическим типам переменных, используемым в языке SQL. Для обеспечения согласованности результатов выполнения операторов & и | с имеющим три значения логическим типом языка SQL предусмотрены следующие предварительно определенные операторы:

bool? operator &(bool? x, bool? y)

bool? operator |(bool? x, bool? y)

Результаты выполнения этих операторов приведены в следующей таблице:

X

y

x&y

x|y

True

true

True

true

True

false

False

true

True

null

Null

true

False

true

False

true

False

false

False

false

False

null

False

null

Null

true

Null

true

Null

false

False

null

Null

null

Null

null

X

y

x&y

x|y

true

true

true

true

true

false

false

true

true

null

null

true

false

true

false

true

false

false

false

false

false

null

false

null

null

true

null

true

null

false

false

null

null

null

null

null

How to: Identify a Nullable Type

You can use the C# typeof operator to create a Type object that represents a Nullable type:

System.Type type = typeof(int?);

You can also use the classes and methods of the System.Reflection namespace to generate Type objects that represent Nullable types. However, if you try to obtain type information from Nullable variables at runtime by using the GetType method or the is operator, the result is a Type object that represents the underlying type, not the Nullable type itself.

Calling GetType on a Nullable type causes a boxing operation to be performed when the type is implicitly converted to Object. Therefore GetType always returns a Type object that represents the underlying type, not the Nullable type.

int? i = 5;

Type t = i.GetType();

Console.WriteLine(t.FullName); //"System.Int32"

The C# is operator also operates on a Nullable's underlying type. Therefore you cannot use is to determine whether a variable is a Nullable type. The following example shows that the is operator treats a Nullable<int> variable as an int.

static void Main(string[] args)

{

int? i = 5;

if (i is int) // true

//…

}

Example

Use the following code to determine whether a Type object represents a Nullable type. Remember that this code always returns false if the Type object was returned from a call to GetType, as explained earlier in this topic.

if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) {…}