PART I
C h a p t e r 1 6 :
N a m e s p a c e s , t h e P r e p r o c e s s o r , a n d A s s e m b l i e s
443
PART IPART I
using Counter;
This brings the
Counter
namespace into view. The second change is that it is no longer
necessary to qualify
CountDown
with
Counter
, as this statement in
Main( )
shows:
CountDown cd1 = new CountDown(10);
Because
Counter
is now in view,
CountDown
can be used directly.
The program illustrates one other important point: Using one namespace does not
override another. When you bring a namespace into view, it simply lets you use its contents
without qualification. Thus, in the example, both
System
and
Counter
have been brought
into view.
A Second Form of using
The
using
directive has a second form that creates another name, called an alias, for a type
or a namespace. This form is shown here:
using
alias
=
name
;
Here,
alias
becomes another name for the type (such as a class type) or namespace specified
by
name.
Once the alias has been created, it can be used in place of the original name.
Here the example from the preceding section has been reworked so that an alias for
Counter.CountDown
called
MyCounter
is created:
// Demonstrate a using alias.
using System;
// Create an alias for Counter.CountDown.
using MyCounter = Counter.CountDown;
// Declare a namespace for counters.
namespace Counter {
// A simple countdown counter.
class CountDown {
int val;
public CountDown(int n) {
val = n;
}
public void Reset(int n) {
val = n;
}
public int Count() {
if(val > 0) return val--;
else return 0;
}
}
}
class NSDemo4 {
www.freepdf-books.com
444
P a r t I :
T h e C # L a n g u a g e
static void Main() {
// Here, MyCounter is used as a name for Counter.CountDown.
MyCounter cd1 = new MyCounter(10);
int i;
do {
i = cd1.Count();
Console.Write(i + " ");
} while(i > 0);
Console.WriteLine();
MyCounter cd2 = new MyCounter(20);
do {
i = cd2.Count();
Console.Write(i + " ");
} while(i > 0);
Console.WriteLine();
cd2.Reset(4);
do {
i = cd2.Count();
Console.Write(i + " ");
} while(i > 0);
Console.WriteLine();
}
}
The
MyCounter
alias is created using this statement:
using MyCounter = Counter.CountDown;
Once
MyCounter
has been specified as another name for
Counter.CountDown
, it can be
used to declare objects without any further namespace qualification. For example, in the
program, this line
MyCounter cd1 = new MyCounter(10);
creates a
CountDown
object.
Namespaces Are Additive
There can be more than one namespace declaration of the same name. This allows a
namespace to be split over several files or even separated within the same file. For example,
the following program defines two
Counter
namespaces. One contains the
CountDown
class. The other contains the
CountUp
class. When compiled, the contents of both
Counter
namespaces are added together.
// Namespaces are additive.
using System;
// Bring Counter into view.
using Counter;
www.freepdf-books.com
Do'stlaringiz bilan baham: |