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

Chapter 14 Using Garbage Collection and Resource Management

267

Notice the following features of the Example class:

The class implements the IDisposable interface.

The destructor calls Dispose.

The Dispose method is public and can be called at any time.

The Dispose method can safely be called multiple times. The variable disposed indicates whether the method has already been run. The scarce resource is released only the first time the method runs.

The Dispose method calls the static GC.SuppressFinalize method. This method stops the garbage collector from calling the destructor on this object, because the object has now been finalized.

All the regular methods of the class (such as SomeBehavior) check to see whether the object has already been disposed. If it has, they throw an exception.

Making Code Exception-Safe

In the following exercise, you will rewrite a small piece of code to make the code exceptionsafe. The code opens a text file, reads its contents one line at a time, writes these lines to a text box on a form on the screen, and then closes the text file. However, if an exception arises

as the file is read or as the lines are written to the text box, the call to close the text file will be bypassed. You will rewrite the code to use a using statement instead, ensuring that the

code is exception-safe.

Write a using statement

1.Start Microsoft Visual Studio 2008 if it is not already running.

2.Open the UsingStatement project, located in the \Microsoft Press\Visual CSharp Step by Step\Chapter 14\UsingStatement folder in your Documents folder.

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

A Windows Presentation Foundation (WPF) form appears.

4.On the form, click Open File.

5.In the Open dialog box, move to the \Microsoft Press\Visual CSharp Step by Step\ Chapter 14\UsingStatement\UsingStatement folder in your Documents folder, and select the Window1.xaml.cs source file.

This is the source file for the application itself.

268Part II Understanding the C# Language

6.Click Open.

The contents of the file are displayed in the form, as shown here:

7.Close the form to return to Visual Studio 2008.

8.Open the Window1.xaml.cs file in the Code and Text Editor window, and then locate the openFileDialogFileOk method.

The method looks like this:

private void openFileDialogFileOk(object sender, System.ComponentModel.CancelEventArgs e)

{

string fullPathname = openFileDialog.FileName; FileInfo src = new FileInfo(fullPathname); fileName.Text = src.Name;

source.Clear();

TextReader reader = new StreamReader(fullPathname); string line;

while ((line = reader.ReadLine()) != null)

{

source.Text += line + “\n”;

}

reader.Close();

}

Chapter 14 Using Garbage Collection and Resource Management

269

The variables fileName, openFileDialog, and source are three private fields of the Window1 class. The problem with this code is that the call to reader.Close is not guaran-

teed to execute. If an exception occurs after opening the file, the method will terminate with an exception, but the file will remain open until the application finishes.

9.Modify the openFileDialogFileOk method, and wrap the code that processes the file in a using statement (including opening and closing braces), as shown in bold here. Remove the statement that closes the TextReader object.

private void openFileDialogFileOk(object sender, System.ComponentModel.CancelEventArgs e)

{

string fullPathname = openFileDialog.FileName; FileInfo src = new FileInfo(fullPathname); fileName.Text = src.Name;

source.Clear();

using (TextReader reader = new StreamReader(fullPathname))

{

string line;

while ((line = reader.ReadLine()) != null)

{

source.Text += line + “\n”;

}

}

}

You no longer need to call reader.Close because it will be invoked automatically by the Dispose method of the StreamReader class when the using statement completes.

This applies whether the using statement finishes naturally or terminates because of an exception.

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

11.Verify that the application works as before, and then close the form.

If you want to continue to the next chapter:

Keep Visual Studio 2008 running, and turn to Chapter 15. 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.

270

Part II Understanding the C# Language

Chapter 14 Quick Reference

To

 

Do this

Write a destructor

Write a method whose name is the same as the name of the class and is pre-

 

 

fixed with a tilde (~). The method must not have an access modifier (such as

 

 

public) and cannot have any parameters or return a value. For example:

 

 

class Example

 

 

{

 

 

~Example()

 

 

{

 

 

...

 

 

}

 

 

}

 

 

Call a destructor

You can’t call a destructor. Only the garbage collector can call a destructor.

 

 

Force garbage collection

Call System.GC.Collect.

(not recommended)

 

Release a resource at a known point in time (but at the risk of memory leaks if an exception interrupts the execution)

Write a disposal method (a method that disposes of a resource) and call it explicitly from the program. For example:

class TextReader

{

...

public virtual void Close()

{

...

}

}

class Example

{

void Use()

{

TextReader reader = ...; // use reader reader.Close();

}

}

Chapter 14 Using Garbage Collection and Resource Management

271

Release a resource at a known point in time in an exception-safe manner (the recommended approach)

Release the resource with a using statement. For example:

class TextReader : IDisposable

{

...

public virtual void Dispose()

{

// calls Close

}

public virtual void Close()

{

...

}

}

class Example

{

void Use()

{

using (TextReader reader = ...)

{

// use reader

}

}

}

Microsoft Visual C# 2008 Step by Step

Part III

Creating Components

In this part:

Chapter 15. Implementing Properties to Access Fields . . . . . . . . . . . . . . . . . . . . 275 Chapter 16. Using Indexers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295 Chapter 17. Interrupting Program Flow and Handling Events. . . . . . . . . . . . . . . 311 Chapter 18. Introducing Generics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333 Chapter 19. Enumerating Collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355 Chapter 20. Querying In-Memory Data By Using Query Expressions . . . . . . . . 371 Chapter 21. Operator Overloading. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395

273

Chapter 15

Implementing Properties to

Access Fields

After completing this chapter, you will be able to:

Encapsulate logical fields by using properties.

Control read access to properties by declaring get accessors.

Control write access to properties by declaring set accessors.

Create interfaces that declare properties.

Implement interfaces containing properties by using structures and classes.

Generate properties automatically based on field definitions.

Use properties to initialize objects.

The first two parts of this book have introduced the core syntax of the C# language and have shown you how to use C# to build new types using structures, enumerations, and classes. You have also seen how the runtime manages the memory used by variables and objects when

a program runs, and you should now understand the life cycle of C# objects. The chapters in Part III, “Creating Components,” build on this information, showing you how to use C# to create reusable components—functional classes that you can reuse in many different applications.

This chapter looks at how to define and use properties to hide fields in a class. Previous chapters have emphasized that you should make the fields in a class private and provide methods to store values in them and to retrieve their values. This approach provides safe and controlled access to fields and enables you to encapsulate additional logic and rules concerning the values that are permitted. However, the syntax for accessing a field in this way is unnatural. When you want to read or write a variable, you normally use an assignment statement, so calling a method to achieve the same effect on a field (which is, after all, just a variable) feels a little clumsy. Properties are designed to alleviate this awkwardness.

275

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