Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C# 2008 Step by Step.pdf
Скачиваний:
26
Добавлен:
25.03.2016
Размер:
13.96 Mб
Скачать

292 Part III Creating Components

These statements display the values of the NumSides and SideLength properties for each Polygon object.

8.On the Debug menu, click Start Without Debugging.

Verify that the program builds and runs, writing the message shown here to the console:

9. Press the Enter key to close the application and return to Visual Studio 2008.

You have now seen how to create automatic properties and how to use properties when initializing objects.

If you want to continue to the next chapter:

Keep Visual Studio 2008 running, and turn to Chapter 16.

If you want to exit Visual Studio 2008 now:

On the File menu, click Exit. If you see a Save dialog box, click Yes (if you are using Visual Studio 2008) or Save (if you are using Visual C# 2008 Express Edition) and save the project.

Chapter 15 Quick Reference

To

Declare a read/write property for a structure or class

Do this

Declare the type of the property, its name, a get accessor, and a set accessor. For example:

struct ScreenPosition

{

...

public int X

{

get { ... } set { ... }

}

...

}

Chapter 15 Implementing Properties to Access Fields

293

Declare a read-only property for a structure or class

Declare a property with only a get accessor. For example:

struct ScreenPosition

{

...

public int X

{

get { ... }

}

...

}

Declare a write-only property for a structure or class

Declare a property with only a set accessor. For example:

struct ScreenPosition

{

...

public int X

{

set { ... }

}

...

}

Declare a property in an interface

Declare a property with just the get or set keyword, or both. For example:

 

interface IScreenPosition

 

 

{

no body

 

int X { get; set; } //

 

int Y { get; set; } //

no body

 

}

 

Implement an interface property

In the class or structure that implements the interface, declare the

in a structure or class

property and implement the accessors. For example:

 

struct ScreenPosition : IScreenPosition

 

{

public int X

 

{

}

get { ...

set { ...

}

}

 

public int Y

 

{

 

get { ... } set { ... }

}

}

294

Part III Creating Components

Create an automatic property

In the class or structure that contains the property, define the property

 

 

with empty get and set accessors. For example:

 

 

class Polygon

 

 

{

 

 

public int NumSides { get; set; }

 

 

}

 

 

Use properties to initialize an

Specify the properties and their values as a list enclosed in braces when

object

 

constructing the object. For example:

Triangle tri3 = new Triangle { Side2Length = 12,

Side3Length = 17 };

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