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

CHAPTER 9 STATEMENTS

The using Statement

Certain types of unmanaged objects are limited in number or are expensive with system resources. It's important that when your code is done with them, they be released as soon as possible. The using statement helps simplify the process and ensures that these resources are properly disposed of.

A resource is a class or struct that implements the System.IDisposable interface. Interfaces are covered in detail in Chapter 17—but in short, an interface is a collection of unimplemented function members that classes and structs can choose to implement. The IDisposable interface contains a single method named Dispose.

The phases of using a resource are shown in Figure 9-10 and consist of the following:

Allocating the resource

Using the resource

Disposing of the resource

If an unexpected run-time error occurs during the portion of the code using the resource, the code disposing of the resource might not get executed.

Figure 9-10. Components of using a resource

Note The using statement is different from the using directives. The using directives are covered in Chapter 10.

262

CHAPTER 9 STATEMENTS

Packaging Use of the Resource

The using statement helps reduce the potential problem of an unexpected run-time error by neatly packaging the use of a resource.

There are two forms of the using statement. The first form is the following and is illustrated in Figure 9-11.

The code between the parentheses allocates the resource.

Statement is the code that uses the resource.

The using statement implicitly generates the code to dispose of the resource.

using ( ResourceType Identifier = Expression ) Statement

 

 

Allocates resource

Uses resource

Unexpected run-time errors are called exceptions and are covered in Chapter 11. The standard way of handling the possibility of exceptions is to place the code that might cause an exception in a try block and place any code that must be executed, whether or not there is an exception, into a finally block.

This form of the using statement does exactly that. It performs the following:

Allocates the resource

Places Statement in a try block

Creates a call to the resource’s Dispose method and places it in a finally block

Figure 9-11. The effect of the using statement

263

CHAPTER 9 STATEMENTS

Example of the using Statement

The following code uses the using statement twice—once with a class called TextWriter and once with a class called TextReader, both from the System.IO namespace. Both classes implement the IDisposable interface, as required by the using statement.

The TextWriter resource opens a text file for writing and writes a line to the file.

The TextReader resource then opens the same text file and reads and displays the contents, line by line.

In both cases, the using statement makes sure that the objects’ Dispose methods are called.

Notice also the difference between the using statements in Main and the using directives on the first two lines.

using

System;

//

using

DIRECTIVE;

not

using

statement

using

System.IO;

//

using

DIRECTIVE;

not

using

statement

namespace UsingStatement

{

class Program

{

static void Main( )

{

// using statement

using (TextWriter tw = File.CreateText("Lincoln.txt") )

{

tw.WriteLine("Four score and seven years ago, ...");

}

// using statement

using (TextReader tr = File.OpenText("Lincoln.txt"))

{

string InputString;

while (null != (InputString = tr.ReadLine())) Console.WriteLine(InputString);

}

}

}

}

This code produces the following output:

Four score and seven years ago, ...

264

CHAPTER 9 STATEMENTS

Multiple Resources and Nesting

The using statement can also be used with multiple resources of the same type, with the resource declarations separated by commas. The syntax is the following:

Only one type

 

Resource

Resource

 

 

 

 

using ( ResourceType Id1 = Expr1,

Id2 = Expr2, ... ) EmbeddedStatement

For example, in the following code, each using statement allocates and uses two resources:

static void Main()

{

using (TextWriter tw1 = File.CreateText("Lincoln.txt"), tw2 = File.CreateText("Franklin.txt"))

{

tw1.WriteLine("Four score and seven years ago, ..."); tw2.WriteLine("Early to bed; Early to rise ...");

}

using (TextReader tr1 = File.OpenText("Lincoln.txt"), tr2 = File.OpenText("Franklin.txt"))

{

string InputString;

while (null != (InputString = tr1.ReadLine())) Console.WriteLine(InputString);

while (null != (InputString = tr2.ReadLine())) Console.WriteLine(InputString);

}

}

The using statement can also be nested. In the following code, besides the nesting of the using statements, also note that it is not necessary to use a block with the second using statement because it consists of only a single, simple statement.

using ( TextWriter tw1 = File.CreateText("Lincoln.txt") )

{

tw1.WriteLine("Four score and seven years ago, ...");

 

 

using ( TextWriter tw2 = File.CreateText("Franklin.txt") ) //

Nested

tw2.WriteLine("Early to bed; Early to rise ...");

//

Single

}

265

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