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

CHAPTER 12 STRUCTS

Field Initializers Are Not Allowed

Field initializers are not allowed in struct declarations, as shown in the following code:

struct Simple

Not allowed

 

{

 

 

 

 

 

 

public int

x = 0;

// Compile error

public int

y = 10;

// Compile error

}

 

 

 

 

 

Not allowed

 

Structs Are Sealed

Structs are always implicitly sealed, and hence you cannot derive other structs from them.

Since structs do not support inheritance, the use of several of the class member modifiers with struct members would not make sense; thus, they cannot be used in their declarations. The modifiers that cannot be used with structs are the following:

protected

internal

abstract

virtual

Structs themselves are, under the covers, derived from System.ValueType, which is derived from object.

The two inheritance-associated keywords you can use with struct members are the new and override modifiers, when creating a member with the same name as a member of base class System.ValueType, from which all structs are derived.

Boxing and Unboxing

As with other value type data, if you want to use a struct instance as a reference type object, you must make a boxed copy. Boxing and unboxing are explained in Chapter 18.

324

CHAPTER 12 STRUCTS

Structs As Return Values and Parameters

Structs can be used as return values and parameters.

Return value: When a struct is a return value, a copy is created and returned from the function member.

Value parameter: When a struct is used as a value parameter, a copy of the actual parameter struct is created. The copy is used in the execution of the method.

ref and out parameters: If you use a struct as a ref or out parameter, a reference to the struct is passed into the method so that the data members can be changed.

Additional Information About Structs

Allocating structs requires less overhead than creating instances of a class, so using structs instead of classes can sometimes improve performance—but beware of the high cost of boxing and unboxing.

Finally, some last things you should know about structs are the following:

The predefined simple types (int, short, long, and so on), although considered primitives in .NET and C#, are all actually implemented under the covers in .NET as structs.

You can declare partial structs in the same way as partial classes, as described in Chapter 6. Structs, like classes, can implement interfaces, which will be covered in Chapter 17.

325

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