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

CHAPTER 6 MORE ABOUT CLASSES

Object Initializers

So far in the text, you’ve seen that an object-creation expression consists of the keyword new followed by a class constructor and its parameter list. An object initializer extends that syntax by placing a list of member initializations at the end of the expression. This allows you to set the values of fields and properties when creating a new instance of an object.

The syntax has two forms, as shown here. One form includes the constructor’s argument list, and the other doesn’t. Notice that the first form doesn’t even use the parentheses that would enclose the argument list.

Object initializer

new TypeName { FieldOrProp = InitExpr, FieldOrProp = InitExpr, ...} new TypeName(ArgList) { FieldOrProp = InitExpr, FieldOrProp = InitExpr, ...}

 

Member initializer

 

Member initializer

For example, for a class named Point with two public integer fields X and Y, you could use the following expression to create a new object:

new Point { X =

5, Y =

6

};

 

 

 

Init X

Init Y

 

Important things to know about object initializers are the following:

The fields and properties being initialized must be accessible to the code creating the object. For example, in the previous code, X and Y must be public.

The initialization occurs after the constructor has finished execution, so the values might have been set in the constructor and then reset to the same or different value in the object initialize.

138

static void Main( )
{

CHAPTER 6 MORE ABOUT CLASSES

The following code shows an example of using an object initializer. In Main, pt1 calls just the constructor, which sets the values of its two fields. For pt2, however, the constructor sets the fields’ values to 1 and 2, and the initializer changes them to 5 and 6.

public class Point

{

public int X = 1; public int Y = 2;

}

class Program

{

Object initializer

Point pt1 = new Point(); _______↓__ ____

Point pt2 = new Point { X = 5, Y = 6 }; Console.WriteLine("pt1: {0}, {1}", pt1.X, pt1.Y); Console.WriteLine("pt2: {0}, {1}", pt2.X, pt2.Y);

}

}

This code produces the following output:

pt1: 1, 2 pt2: 5, 6

139

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