Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Daniel Solis - Illustrated C# 2010 - 2010.pdf
Скачиваний:
16
Добавлен:
11.06.2015
Размер:
11.23 Mб
Скачать

CHAPTER 25 OTHER TOPICS

For example, the following code uses this struct and creates variables of both the struct and the corresponding nullable type. In the third and fourth lines of code, the values of the struct’s variables are read directly. In the fifth and sixth lines, they must be read from the value returned by the nullable’s Value property.

MyStruct mSStruct

= new MyStruct(6,

11);

// Variable of struct

MyStruct? mSNull

= new MyStruct(5,

10);

// Variable of nullable type

 

 

Struct access

 

 

 

 

 

 

 

Console.WriteLine("mSStruct.X: {0}",

 

mSStruct.X);

Console.WriteLine("mSStruct.Y: {0}",

 

mSStruct.Y);

Console.WriteLine("mSNull.X: {0}",

 

mSNull.Value.X);

Console.WriteLine("mSNull.Y: {0}",

 

mSNull.Value.Y);

 

 

 

 

 

 

Nullable type access

Nullable<T>

Nullable types are implemented by using a .NET type called System.Nullable<T>, which uses the C# generics feature.

The question mark syntax of C# nullable types is just shortcut syntax for creating a variable of type Nullable<T>, where T is the underlying type. Nullable<T> takes the underlying type, embeds it in a structure, and provides the structure with the properties, methods, and constructors of the nullable type.

You can use either the generics syntax of Nullable<T> or the C# shortcut syntax. The shortcut syntax is easier to write and to understand and is less prone to errors.

The following code uses the Nullable<T> syntax with struct MyStruct, declared in the preceding example, to create a variable called mSNull of type Nullable<MyStruct>:

Nullable<MyStruct> mSNull = new Nullable<MyStruct>();

The following code uses the question mark syntax but is semantically equivalent to the Nullable<T> syntax:

MyStruct? mSNull = new MyStruct();

678

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]