楼主: bnso

Introduction to C# Programming

[复制链接]
论坛徽章:
49
NBA季后赛之星
日期:2014-10-19 19:51:33蓝锆石
日期:2014-10-19 19:51:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33问答徽章
日期:2014-04-15 10:41:44优秀写手
日期:2014-07-24 06:00:11保时捷
日期:2014-10-19 19:51:33三菱
日期:2014-10-19 19:51:33
91#
 楼主| 发表于 2006-8-13 21:30 | 只看该作者
8 Module 8: Using Reference-Type Variables
Comparing Values and Comparing References
n Comparing Value Types
l == and != compare values
n Comparing Reference Types
l == and != compare the references, not the values
?? 11.0.0 22..00
?? 11.0.0 22..00
Different
The equality (==) and inequality (!=) operators might not work in the way you
expect for reference variables.
Comparing Value Types
For value types, you can use the == and != operators to compare values.
Comparing Reference Types
For reference types, you can use the == and != operators to compare references.
When comparing references with the == operator, you are determining whether
the two reference variables are referring to the same object. You are not
comparing the contents of the objects to which the variables refer.
Module 8: Using Reference-Type Variables 9
Consider the following example, in which two coordinate variables are created
and initialized to the same values:
coordinate c1= new coordinate( );
coordinate c2= new coordinate( );
c1.x = 1.0;
c1.y = 2.0;
c2.x = 1.0;
c2.y = 2.0;
if (c1 == c2)
Console.WriteLine("Same";
else
Console.WriteLine("Different";
The output from this code is “Different.” Even though the objects that c1 and c2
are referring to have the same values, they are references to different objects, so
== returns false .
You cannot use the other relational operators (<, >, <=, and >=) for references
because they are not defined in C#.
10 Module 8: Using Reference-Type Variables
Multiple References to the Same Object
n Two References Can Refer to the Same Object
l Two ways to access the same object for read/write
coordinate c1= new coordinate( );
coordinate c2;
c1.x = 2.3; c1.y = 7.6;
c2 = c1;
Console.WriteLine(c1.x + " , " + c1.y);
Console.WriteLine(c2.x + " , " + c2.y);
coordinate c1= new coordinate( );
coordinate c2;
c1.x = 2.3; c1.y = 7.6;
c2 = c1;
Console.WriteLine(c1.x + " , " + c1.y);
Console.WriteLine(c2.x + " , " + c2.y);
??
22..33 77..66
??
c1
c2
Two reference variables can refer to the same object because reference
variables hold a reference to the data. This means that you can write data
through one reference and read the same data through another reference.
Multiple References to the Same Object
In the following example, the variable c1 is initialized to point to a new
instance of the class, and its member variables x and y are initialized. Then c1 is
copied to c2. Finally, the values in the objects that c1 and c2 reference are
displayed.
coordinate c1 = new coordinate( );
coordinate c2;
c1.x = 2.3;
c1.y = 7.6;
c2 = c1;
Console.WriteLine(c1.x + " , " + c1.y);
Console.WriteLine(c2.x + " , " + c2.y);
The output of this program is as follows:
2.3 , 7.6
2.3 , 7.6
Assigning c2 to c1 copies the reference so that both variables are referencing
the same instance. Therefore, the values printed for the member variables of c1
and c2 are the same.
Module 8: Using Reference-Type Variables 11
Writing and Reading the Same Data Through Different
References
In the following example, an assignment has been added immediately before
the calls to Console.WriteLine.
coordinate c1 = new coordinate( );
coordinate c2;
c1.x = 2.3;
c1.y = 7.6;
c2 = c1;
c1.x = 99; // This is the extra statement
Console.WriteLine(c1.x + " , " + c1.y);
Console.WriteLine(c2.x + " , " + c2.y);
The output of this program is as follows:
99 , 7.6
99 , 7.6
This shows that the assignment of 99 to c1.x has also changed c2.x. Because the
reference in c1 was previously assigned to c2, a program can write data through
one reference and read the same data through another reference.

使用道具 举报

回复
论坛徽章:
49
NBA季后赛之星
日期:2014-10-19 19:51:33蓝锆石
日期:2014-10-19 19:51:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33问答徽章
日期:2014-04-15 10:41:44优秀写手
日期:2014-07-24 06:00:11保时捷
日期:2014-10-19 19:51:33三菱
日期:2014-10-19 19:51:33
92#
 楼主| 发表于 2006-8-13 21:30 | 只看该作者
12 Module 8: Using Reference-Type Variables
Using References as Method Parameters
n References Can Be Used as Parameters
l When passed by reference, data being referenced may
be changed
static void PassCoordinateByValue(coordinate c)
{
c.x++; c.y++;
}
static void PassCoordinateByValue(coordinate c)
{
c.x++; c.y++;
}
loc.x = 2; loc.y = 3;
PassCoordinateByValue(loc);
Console.WriteLine(loc.x + " , " + loc.y);
loc.x = 2; loc.y = 3;
PassCoordinateByValue(loc);
Console.WriteLine(loc.x + " , " + loc.y);
22 33 33 44
??
??
You can pass reference variables in and out of a method.
References and Methods
You can pass reference variables into methods as parameters by using any of
the three calling mechanisms:
n By value
n By reference
n Output parameters
The following example shows a method that passes three coordinate references.
The first is passed by value, the second is passed by reference, and the third is
an output parameter. The return value of the method is a coordinate reference.
static coordinate Example(
coordinate ca,
ref coordinate cb,
out coordinate cc)
{
// ...
}
Module 8: Using Reference-Type Variables 13
Passing References by Value
When you use a reference variable as a value parameter, the method receives a
copy of the reference. This means that for the duration of the call there are two
references referencing the same object. It also means that any changes to the
method parameter cannot affect the calling reference. For example, the
following code displays the values 0 , 0:
static void PassCoordinateByValue(coordinate c)
{
c = new coordinate( );
c.x = c.y = 22.22;
}
coordinate loc = new coordinate( );
PassCoordinateByValue(loc);
Console.WriteLine(loc.x + " , " + loc.y);
Passing References by Reference
When you use a reference variable as a ref parameter, the method receives the
actual reference variable. In contrast to passing by value, in this case there is
only one reference. The method does not make its own copy. This means that
any changes to the method parameter will affect the calling reference. For
example, the following code displays the values 33.33 , 33.33:
static void PassCoordinateByRef(ref coordinate c)
{
c = new coordinate( );
c.x = c.y = 33.33;
}
coordinate loc = new coordinate( );
PassCoordinateByRef(ref loc);
Console.WriteLine(loc.x + "," + loc.y);
Passing References by Output
When you use a reference variable as an out parameter, the method receives the
actual reference variable. In contrast to passing by value, in this case there is
only one reference. The method does not make its own copy. Passing by out is
similar to passing by ref except that the method must assign to the out
parameter. For example, the following code displays the values 44.44 , 44.44:
static void PassCoordinateByOut(out coordinate c)
{
c = new coordinate( );
c.x = c.y = 44.44;
}
coordinate loc = new coordinate( );
PassCoordinateByOut(out loc);
Console.WriteLine(loc.x + "," + loc.y);
14 Module 8: Using Reference-Type Variables
Passing References into Methods
Variables of reference types do not hold the value directly, but hold a reference
to the value instead. This also applies to method parameters, and this means that
the pass-by-value mechanism can produce unexpected results.
Using the coordinate class as an example, consider the following method:
static void PassCoordinateByValue(coordinate c)
{
c.x++;
c.y++;
}
The coordinate parameter c is passed by value. In the method, both the x and y
member variables are incremented. Now consider the following code that calls
the PassCoordinateByValue method:
coordinate loc = new coordinate( );
loc.x = 2;
loc.y = 3;
PassCoordinateByValue(loc);
Console.WriteLine(loc.x + " , " + loc.y);
The output of this code is the following:
3 , 4
This shows that the values referenced by loc have been changed by the method.
This might seem to be in conflict with the explanation of pass by value given
previously in the course, but in fact it is consistent. The reference variable loc is
copied into the parameter c and cannot be changed by the method, but the
memory to which it refers is not copied and is under no such restriction. The
variable loc still refers to the same area of memory, but that area of memory
now contains different data.

使用道具 举报

回复
论坛徽章:
49
NBA季后赛之星
日期:2014-10-19 19:51:33蓝锆石
日期:2014-10-19 19:51:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33问答徽章
日期:2014-04-15 10:41:44优秀写手
日期:2014-07-24 06:00:11保时捷
日期:2014-10-19 19:51:33三菱
日期:2014-10-19 19:51:33
93#
 楼主| 发表于 2006-8-13 21:30 | 只看该作者
Module 8: Using Reference-Type Variables 15
u Using Common Reference Types
n Exception Class
n String Class
n Common String Methods, Operators, and Properties
n String Comparisons
n String Comparison Operators
A number of reference-type classes are built in to the C# language. In this
section, you will review some familiar built-in classes and learn more about
how they work.
You can also use these built-in classes as models when creating your own
classes.
16 Module 8: Using Reference-Type Variables
Exception Class
n Exception Is a Class
n Exception Objects Are Used to Raise Exceptions
l Create an Exception object by using new
l Throw the object by using throw
n Exception Types Are Subclasses of Exception
You create and throw Exception objects to raise exceptions.
Exception Class.
Exception is the name of a class provided in the .NET Framework.
Exception Objects
Only objects of Exception type can be thrown with throw and caught with
catch. In other respects, the Exception class is like other reference types.
Exception Types
Exception represents a generic fault in an application. There are also specific
exception types (such as InvalidCastException). There are classes that inherit
from Exception that represent each of these specific exceptions.
Module 8: Using Reference-Type Variables 17
String Class
n Multiple Character Unicode Data
n Shorthand for System.String
n Immutable
string s = "Hello";
s[0] = 'c'; // Compile-time error
string s = "Hello";
s[0] = 'c'; // Compile-time error
In C#, the string type is used for processing multiple character Unicode
character data. (The char type, by comparison, is a value type that handles
single characters.)
The type name string is a shortened name for the System.String class. The
compiler can process this shortened form; therefore string and System.String
can be used interchangeably.
The String class represents an immutable string of characters. An instance of
String is immutable: the text of a string cannot be modified once it has been
created. Methods that might appear at first sight to modify a string value
actually return a new instance of string that contains the modification.
The StringBuilder class is often used in partnership with the String class.
A StringBuilder builds an internally modifiable string that can be converted
into an immutable String when complete. StringBuilder removes the need to
repeatedly create temporary immutable Strings and can provide improved
performance.
The System.String class has many methods. This course will not provide a full
tutorial for string processing, but it will list some of the more useful methods.
For further details, consult the .NET Framework SDK Help documents.
Tip
18 Module 8: Using Reference-Type Variables
Common String Methods, Operators, and Properties
n Brackets
n Insert Method
n Length Property
n Copy Method
n Concat Method
n Trim Method
n ToUpper and ToLower Methods
Brackets [ ]
You can extract a single character at a given position in a string by using the
string name followed by the index in brackets ([ and ]). This process is similar
to using an array. The first character in the string has an index of zero.
The following code provides an example:
string s = "Alphabet"
char firstchar = s[2]; // 'p'
Strings are immutable, so assigning a character by using brackets is not
permitted. Any attempt to assign a character to a string in this way will generate
a compile-time error, as shown:
s[2] = '*'; // Not valid
Insert Method
If you want to insert characters into a string variable, use the Insert instance
method to return a new string with a specified value inserted at a specified
position in this string. This method takes two parameters: the position of the
start of the insertion and the string to insert.
The following code provides an example:
string s = "C is great!";
s = s.Insert(2, "Sharp ";
Console.WriteLine(s); // C Sharp is great!

使用道具 举报

回复
论坛徽章:
49
NBA季后赛之星
日期:2014-10-19 19:51:33蓝锆石
日期:2014-10-19 19:51:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33问答徽章
日期:2014-04-15 10:41:44优秀写手
日期:2014-07-24 06:00:11保时捷
日期:2014-10-19 19:51:33三菱
日期:2014-10-19 19:51:33
94#
 楼主| 发表于 2006-8-13 21:31 | 只看该作者
Module 8: Using Reference-Type Variables 19
Length Property
The Length property returns the length of a string as an integer, as shown:
string msg = "Hello";
int slen = msg.Length; // 5
Copy Method
The Copy class method creates a new string by copying another string. The
Copy method makes a duplicate of a specified string.
The follow ing code provides an example:
string s1 = "Hello";
string s2 = String.Copy(s1);
Concat Method
The Concat class method creates a new string from one or more strings or
objects represented as strings.
The following code provides an example:
string s3 = String.Concat("a", "b", "c", "d", "e", "f", "g";
The + operator is overloaded for strings, so the example above can be re-written
as follows:
string s = "a" + "b" + "c" + "d" + "e" + "f" + "g";
Console.WriteLine(s);
Trim Method
The Trim instance method removes all of the specified characters or white
space from the beginning and end of a string.
The following code provides an example:
string s = " Hello ";
s = s.Trim( );
Console.WriteLine(s); // "Hello"
ToUpper and ToLower Methods
The ToUpper and ToLowe r instance methods return a string with all
characters converted to uppercase and lowercase, respectively, as shown:
string sText = "How to Succeed ";
Console.WriteLine(sText.ToUpper( )); // HOW TO SUCCEED
Console.WriteLine(sText.ToLower( )); // how to succeed
20 Module 8: Using Reference-Type Variables
String Comparisons
n Equals Method
l Value comparison
n Compare Method
l More comparisons
l Case-insensitive option
l Dictionary ordering
n Locale-Specific Compare Options
You can use the == and != operators on string variables to compare string
contents.
Equals Method
The System.String class contains an instance method called Equals, which can
be used to compare two strings for equality. The method returns a bool value
that is true if the strings are the same and false otherwise. This method is
overloaded and can be used as an instance method or a static method. The
following example shows both forms.
string s1 = "Welcome";
string s2 = "Welcome";
if (s1.Equals(s2))
Console.WriteLine("The strings are the same";
if (String.Equals(s1,s2))
Console.WriteLine("The strings are the same";
Module 8: Using Reference-Type Variables 21
Compare Method
The Compare method compares two strings lexically; that is, it compares the
strings according to their sort order. The return value from Compare is as
follows:
n A negative integer if the first string comes before the second
n 0 if the strings are the same
n A positive integer if the first string comes after the second
string s1 = "Tintinnabulation";
string s2 = "Velocipede";
int comp = String.Compare(s1,s2); // Negative return
By definition, any string, including an empty string, compares greater than a
null reference, and two null references compare equal to each other.
Compare is overloaded. There is a version with three parameters, the third of
which is a bool value that specifies whether the case should be ignored in the
comparison. The following example shows a case-insensitive comparison:
s1 = "cabbage";
s2 = "Cabbage";
comp = String.Compare(s1, s2, true); // Ignore case
Locale-Specific Compare Options
The Compare method has overloaded versions that allow string comparisons
based on language-specific sort orders. This can be useful when writing
applications for an international market. Further discussion of this feature is
beyond the scope of the course. For more information, search for
“System.Globalization namespace” and “CultureInfo class” in the .NET
Framework SDK Help documents.

使用道具 举报

回复
论坛徽章:
49
NBA季后赛之星
日期:2014-10-19 19:51:33蓝锆石
日期:2014-10-19 19:51:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33问答徽章
日期:2014-04-15 10:41:44优秀写手
日期:2014-07-24 06:00:11保时捷
日期:2014-10-19 19:51:33三菱
日期:2014-10-19 19:51:33
95#
 楼主| 发表于 2006-8-13 21:31 | 只看该作者
22 Module 8: Using Reference-Type Variables
String Comparison Operators
n The == and != Operators Are Overloaded for Strings
n They Are Equivalent to String.Equals and !String.Equals
string a = "Test";
string b = "Test";
if (a == b) ... // Returns true
string a = "Test";
string b = "Test";
if (a == b) ... // Returns true
The == and != operators are overloaded for the String class. You can use these
operators to examine the contents of strings.
string a = "Test";
string b = "Test";
if (a == b) ... // Returns true
The following operators and methods are equivalent:
n The == operator is equivalent to the String.Equals method.
n The != operator is equivalent to the !String.Equals method.
The other relational operators (<, >, <=, and >=) are not overloaded for the
String class.
Module 8: Using Reference-Type Variables 23
u The Object Hierarchy
n The object Type
n Common Methods
n Reflection
The C# classes are arranged in a hierarchy with the Object class at the top. The
object type therefore describes the common behavior for all reference types in
the C# language.
In this section, you will learn about the object type and how the object
hierarchy works.
24 Module 8: Using Reference-Type Variables
The object Type
n Synonym for System.Object
n Base Class for All Classes
Exception
InvalidCastException
MyClass
Object
String
The object type is the base class for all types in C#.
System.Object
The object keyword is a synonym for the System.Object class in the .NET
Framework. Anywhere the keyword object appears, the class name
System.Object can be substituted. Because of its convenience, the shorter form
is more common.
Base Class
All classes inherit from object either directly or indirectly. This includes the
classes you write in your application and those classes that are part of the
system framework. When you declare a class with no explicit parent, you are
actually inheriting from object.
Module 8: Using Reference-Type Variables 25
Common Methods
n Common Methods for All Reference Types
l ToString method
l Equals method
l GetType method
l Finalize method
The object type has a number of common methods that are inherited by all
other reference types.
Common Methods for All Reference Types
The object type provides a number of common methods. Because every
reference type inherits from object, every other reference type in C# has these
methods too. These common methods include the following:
n ToString
n Equals
n GetType
n Finalize
26 Module 8: Using Reference-Type Variables
ToString Method
The ToString method returns a string that represents the current object.
The default implementation, as found in the Object class, returns the type name
of the class. The following example uses the coordinate example class defined
earlier:
coordinate c = new coordinate( );
Console.WriteLine(c.ToString( ));
This example will display “coordinate” on the console.
However, you c an override the ToString method in class coordinate to render
objects of that type into something more meaningful, such as a string containing
the values held in the object.
Equals Method
The Equals method determines whether the specified object is the same
instance as the current object. The default implementation of Equals supports
reference equality only, as you have already seen.
Subclasses can override this method to support value equality instead.
GetType Method
This method allows extraction of run-time type information from an object. It is
discussed in more detail in the Data Conversions section later in this module.
Finalize Method
This method is called by the run-time system when memory allocated to a
reference is released.

使用道具 举报

回复
论坛徽章:
49
NBA季后赛之星
日期:2014-10-19 19:51:33蓝锆石
日期:2014-10-19 19:51:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33问答徽章
日期:2014-04-15 10:41:44优秀写手
日期:2014-07-24 06:00:11保时捷
日期:2014-10-19 19:51:33三菱
日期:2014-10-19 19:51:33
96#
 楼主| 发表于 2006-8-13 21:31 | 只看该作者
Module 8: Using Reference-Type Variables 27
Reflection
n You Can Query the Type of an Object
n System.Reflection Namespace
n The typeof Operator Returns a Type Object
l Compile-time classes only
n GetType Method in System.reflection
l Run-time class information
You can obtain information about the type of an object by using a mechanism
called reflection.
The reflection mechanism in C# is handled by the System.Reflection
namespace in the .NET Framework. This namespace contains classes and
interfaces that provide a view of types, methods, and fields.
The System.Type class provides methods for obtaining information about a
type declaration, such as the constructors, methods, fields, properties, and
events of a class. A Type object that represents a type is unique; that is, two
Type object references refer to the same object only if they represent the same
type. This allows comparison of Type objects through reference comparisons
(the == and != operators).
28 Module 8: Using Reference-Type Variables
The typeof Operator
At compile time, you can use the typeof operator to return the type information
from a given type name.
The following example retrieves run-time type information for the type byte,
and displays the type name to the console.
using System;
using System.Reflection;
Type t = typeof(byte);
Console.WriteLine("Type: {0}", t);
The following example displays more detailed information about a class.
Specifically, it lists the methods for that class.
using System;
using System.Reflection;
Type t = typeof(string); // Get type information
MethodInfo[ ] mi = t.GetMethods( );
foreach (MethodInfo m in mi) {
Console.WriteLine("Method: {0}", m);
}
GetType Method
The typeof operator only works on classes that exist at compile time. If you
need type information at run time, you can use the GetType method of the
Object class.
For more information about reflection, search for “System.Reflection” in
the .NET Framework SDK Help documents.
Module 8: Using Reference-Type Variables 29
u Namespaces in the .NET Framework
n System.IO Namespace
n System.XML Namespace
n System.Data Namespace
n Other Useful Namespaces
The .NET Framework provides common language services to a variety of
application development tools. The classes in the framework provide an
interface to the Common Language Runtime, the operating system, and the
network.
In this section, you will learn how to use some of the common namespaces
within the framework. You are likely to use these namespaces on a regular basis,
so it is important to be familiar with them.
The .NET Framework is large and powerful, and full coverage of every feature
is beyond the scope of this course. For more detailed information, please
consult the Visual Studio.NET and .NET Framework SDK Help documents.
30 Module 8: Using Reference-Type Variables
System.IO Namespace
n Access to File System Input/Output
l File, Directory
l StreamReader, StreamWriter
l FileStream
l BinaryReader, BinaryWriter
The System.IO namespace is important because it contains many classes that
allow an application to perform input and output (I/O) operations in various
ways through the file system.
The System.IO namespace also provides classes that allow an application to
perform input and output operations on files and directories.
The System.IO namespace is large and cannot be explained in detail here.
However, the following list gives an indication of the facilities available:
n The File and Directory classes allow an application to create, delete, and
manipulate directories and files.
n The StreamReader and StreamWriter classes enable a program to access
file contents as a stream of bytes or characters.
n The FileStream class can be used to provide random access to files.
n The BinaryReader and BinaryWriter classes provide a way to save and
load objects to and from streams.

使用道具 举报

回复
论坛徽章:
49
NBA季后赛之星
日期:2014-10-19 19:51:33蓝锆石
日期:2014-10-19 19:51:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33问答徽章
日期:2014-04-15 10:41:44优秀写手
日期:2014-07-24 06:00:11保时捷
日期:2014-10-19 19:51:33三菱
日期:2014-10-19 19:51:33
97#
 楼主| 发表于 2006-8-13 21:31 | 只看该作者
Module 8: Using Reference-Type Variables 31
System.IO Example
A brief example follows, to show how a file can be opened and read as a stream.
The example is not meant to illustrate all of the possible ways in which the
System.IO namespace can be used, but does show how you can perform a
simple file copy operation.
using System;
using System.IO; // Use IO namespace
// ...
StreamReader reader = new StreamReader("infile.txt";
// Text in from file
StreamWriter writer = new StreamWriter("outfile.txt";
// Text out to file
string line;
while ((line = reader.ReadLine( )) != null)
{
writer.WriteLine(line);
}
reader.Close( );
writer.Close( );
To open a file for reading, the code in the example creates a new
StreamReader object and passes the name of the file that needs to be opened
in the constructor. Similarly, to open a file for writing, the example creates a
new StreamWriter object and passes the output file name in its constructor. In
the example, the file names are hard-coded, but they could also be string
variables.
The example program copies a file by reading one line at a time from the input
stream and writing that line to the output stream.
ReadLine and WriteLine might look familiar. The Console class has two
static methods of that name. In the example, the methods are instance methods
of the StreamReader and StreamWriter classes, respectively.
For more information about the System.IO namespace, search for “System.IO
namespace” in the .NET Framework SDK Help documents.
32 Module 8: Using Reference-Type Variables
System.XML Namespace
n XML Support
n Various XML-Related Standards
Applications that need to interact with Extensible Markup Language (XML)
can use the System.XML namespace, which provides standards-based support
for processing XML.
The System.XML namespace supports a number of XML-related standards,
including the following:
n XML 1.0 with document type definition (DTD) support
n XML namespaces
n XML schemas
n XPath expressions
n XSL/T transformations
n DOM Level 2 core
n Simple Object Access Protocol (SOAP) 1.1
The XMLDocument class is used to represent an entire XML document.
Elements and attributes in an XML document are represented in the
XMLElement and XMLAttribute classes.
A detailed discussion of XML namespaces is beyond the scope of this course.
For further information, search for “System.XML namespace” in the .NET
Framework SDK Help documents.
Module 8: Using Reference-Type Variables 33
System.Data Namespace
n System.Data.SQL
l SQL Server specific
n System.Data.ADO
l Interact with OLEDB and ODBC
l Generic database drivers
The System.Data namespace contains classes that constitute the ADO.NET
architecture. The ADO.NET architecture enables you to build components that
efficiently manage data from multiple data sources. ADO.NET provides the
tools to request, update, and reconcile data in n-tier systems.
Within ADO.NET, you can use the DataSet class. In each DataSet, there are
DataTable objects, and each DataTable contains data from a single data
source, such as Microsoft SQL Server? .
The System.Data.SQL namespace provides direct access to SQL Server. Note
that this namespace is specific to SQL Server.
For access to other relational databases and sources of structured data, there is
the System.Data.ADO namespace, which provides high-level access to the
OLEDB and Open Database Connectivity (ODBC) database drivers.
A detailed discussion of the System namespaces is not within the scope of this
course. For further information, search for “System.Data namespace” in
the .NET Framework SDK Help documents.

使用道具 举报

回复
论坛徽章:
49
NBA季后赛之星
日期:2014-10-19 19:51:33蓝锆石
日期:2014-10-19 19:51:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33问答徽章
日期:2014-04-15 10:41:44优秀写手
日期:2014-07-24 06:00:11保时捷
日期:2014-10-19 19:51:33三菱
日期:2014-10-19 19:51:33
98#
 楼主| 发表于 2006-8-13 21:31 | 只看该作者
34 Module 8: Using Reference-Type Variables
Other Useful Namespaces
n System Namespace
n System.Net Namespace
n System.Net.Sockets Namespace
n System.Windows.Forms Namespace
There are many other useful namespaces and classes in the .NET Framework.
This course does not discuss them all at length, but the following information
might be helpful when you search the reference files and documentation:
n The System namespace contains classes that define commonly used value
and reference data types, events and event handlers, interfaces, attributes,
and processing exceptions. Other classes provide services that support data
type conversion, method parameter manipulation, mathematics, remote and
local program invocation, and application management.
n The System.Net namespace provides a simple programming interface to
many of the protocols found on the network today. The System.Net.Sockets
namespace provides an implementation of the Microsoft Windows? Sockets
interface for developers who need to low-level access to Transmission
Control Protocol/Internet Protocol (TCP/IP) network facilities.
n System.WinForms is the graphical user interface (GUI) framework for
Windows applications, and provides support for forms, controls, and event
handlers.
For more information about System namespaces, search for “System
namespace” in the .NET Framework SDK Help documents.
Module 8: Using Reference-Type Variables 35
Lab 8.1: Defining And Using Reference-Type Variables
Objectives
After completing this lab, you will be able to:
n Create reference variables and pass them as method parameters.
n Use the system frameworks.
Prerequisites
Before working on this lab, you should be familiar with the following:
n Creating and using classes
n Calling methods and passing parameters
n Using arrays
Estimated time to complete this lab: 45 minutes
36 Module 8: Using Reference-Type Variables
Exercise 1
Adding an Instance Method with Two Parameters
In Lab 7, you developed a BankAccount class.
In this exercise, you will re-use this class and add a new instance method, called
TransferFrom, which transfers money from a specified account into this one.
If you did not complete Lab 7, you can obtain a copy of the BankAccount class
in the install folder\Labs\Lab08\Starter folder.
? To create the TransferFrom method
1. Open the Bank.sln project in the install folder\Labs\Lab08\Starter\Bank
folder.
2. Edit the BankAccount class as follows:
a. Create a public instance method called TransferFrom in the
BankAccount class.
b. The first parameter is a reference to another BankAccount object, called
accFrom, from which the money is to be transferred.
c. The second parameter is a decimal value, c alled amount, passed by
value and indicating the amount to transfer.
d. The method has no return value.
3. In the body of TransferFrom, add two statements that perform the
following tasks:
a. Debit amount from the balance of accFrom (by using Withdraw).
b. Test to ensure that the withdrawal was successful. If it was, credit
amount to the balance of the current account (by using Deposit).
The BankAccount class should be as follows:
class BankAccount
{
... additional code omitted for clarity ...
public void TransferFrom(BankAccount accFrom, decimal
êamount)
{
if (accFrom.Withdraw(amount))
this.Deposit(amount);
}
}
4. Save and compile your code. Correct any errors.

使用道具 举报

回复
论坛徽章:
49
NBA季后赛之星
日期:2014-10-19 19:51:33蓝锆石
日期:2014-10-19 19:51:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33问答徽章
日期:2014-04-15 10:41:44优秀写手
日期:2014-07-24 06:00:11保时捷
日期:2014-10-19 19:51:33三菱
日期:2014-10-19 19:51:33
99#
 楼主| 发表于 2006-8-13 21:32 | 只看该作者
Module 8: Using Reference-Type Variables 37
? To test the TransferFrom method
1. Open the Test class. This is the test harness.
2. In the Main method, add code to create two BankAccount objects, each
having an initial balance of $100. (Use the Populate method.)
3. Add code to display the type, account number, and current balance of each
account.
4. Add code to call TransferFrom and move $10 from one account to the
other.
5. Add code to display the current balances after the transfer.
The Test class could be as follows:
static void Main( )
{
BankAccount b1 = new BankAccount( );
b1.Populate(100);
BankAccount b2 = new BankAccount( );
b2.Populate(100);
Console.WriteLine("Before transfer";
Console.WriteLine("{0} {1} {2}",
b1.Type( ), b1.Number( ), b1.Balance( ));
Console.WriteLine("{0} {1} {2}",
b2.Type( ), b2.Number( ), b2.Balance( ));
b1.TransferFrom(b2, 10);
Console.WriteLine("After transfer";
Console.WriteLine("{0} {1} {2}",
b1.Type( ), b1.Number( ), b1.Balance( ));
Console.WriteLine("{0} {1} {2}",
b2.Type( ), b2.Number( ), b2.Balance( ));
}
6. Save your work.
7. Compile the project and correct any errors. Run and test the program.
38 Module 8: Using Reference-Type Variables
Exercise 2
Reversing a String
In Module 5, you developed a Utils class that contained a variety of utility
methods.
In this exercise, you will add a new static method called Reverse to the Utils
class. This method takes a string and returns a new string with the characters in
reverse order.
? To create the Reverse method
1. Open the Utils.sln project in the install folder\Labs\Lab08\Starter\Utils
folder.
2. Add a public static method called Reverse to the Utils class, as follows:
a. It has a single parameter called s that is a reference to a string.
b. The method has a void return type.
3. In the Reverse method, create a string variable called sRev to hold the
returned string result. Initialize this string to "".
4. To create a reversed string:
a. Write a loop extracting one character at a time from s. Start at the end
(use the Length property), and work backwards to the start of the string.
You can use array notation ([ ]) to examine an individual character in a
string.
The last character in a string is at position Length – 1. The first
character is at position 0.
b. Append this character to the end of sRev.
Tip
Module 8: Using Reference-Type Variables 39
The Utils class might contain the following:
class Utils
{
... additional methods omitted for clarity ...
//
// Reverse a string
//
public static void Reverse(ref string s)
{
int k;
string sRev = "";
for (k = s.Length – 1; k >= 0 ; k--)
sRev = sRev + s[k];
// Return result to caller
s = sRev;
}
}
? To test the Reverse method
1. Edit the Test class. This class contains the test harness.
2. In the Main method, create a string variable.
3. Read a value into the string variable by using Console.ReadLine.
4. Pass the string into Reverse. Do not forget the ref keyword.
5. Display the value returned by Reverse.
The Test class might contain the following:
static void Main( )
{
string message;
// Get an input string
Console.WriteLine("Enter string to reverse:";
message = Console.ReadLine( );
// Reverse the string
Utils.Reverse(ref message);
// Display the result
Console.WriteLine(message);
}
6. Save your work.
7. Compile the project and correct any errors. Run and test the program.

使用道具 举报

回复
论坛徽章:
49
NBA季后赛之星
日期:2014-10-19 19:51:33蓝锆石
日期:2014-10-19 19:51:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33指数菠菜纪念章
日期:2014-10-19 19:52:33问答徽章
日期:2014-04-15 10:41:44优秀写手
日期:2014-07-24 06:00:11保时捷
日期:2014-10-19 19:51:33三菱
日期:2014-10-19 19:51:33
100#
 楼主| 发表于 2006-8-13 21:32 | 只看该作者
40 Module 8: Using Reference-Type Variables
Exercise 3
Making an Uppercase Copy of a File
In this exercise, you will write a program that prompts the user for the name of
a text file. The program will check that the file exists, displaying a message and
quitting if it does not. The file will be opened and copied to another file (prompt
the user for the file name), but with every character converted to uppercase.
Before you start, you might want to look briefly at the documentation for
System.IO in the .NET Framework SDK Help documents. In particular, look at
the documentation for the StreamReader and StreamWriter classes.
? To create the file -copying application
1. Open the CopyFileUpper.sln project in the install folder\
Labs\Lab08\Starter\CopyFileUpper folder.
2. Edit the CopyFileUpper class and add a using statement for the System.IO
namespace.
3. In the Main method, declare two string variables called sFrom and sTo to
hold the input and output file names.
4. Declare a variable of type StreamReader called srFrom. This variable will
hold the reference to the input file.
5. Declare a variable of type StreamWriter called swTo. This variable will
hold the reference to the output stream.
6. Prompt for the name of the input file, read the name, and store it in the
string variable sFrom.
7. Prompt for the name of the output file, read the name, and store it in the
string variable sTo.
8. The I/O operations that you will use can raise exceptions, so begin a trycatch
block that can catch FileNotFoundException (for non-existent files)
and Exception (for any other exceptions). Print out a meaningful message
for each exception.
9. In the try-catch block, create a new StreamReader object using the input
file name in sFrom, and store it in the StreamReader reference variable
srFrom.
10. Similarly, create a new StreamWriter object using the input file name in
sTo, and store it in the StreamWriter reference variable swTo.
11. Add a while loop that loops if the Peek method of the input stream does not
return -1. Within the loop:
a. Use the ReadLine method on the input stream to read the next line of
input into a string variable called sBuffer.
b. Perform the ToUpper method on sBuffer.
c. Use the WriteLine method to send sBuffer to the output stream.
12. After the loop has finished, close the input and output streams.
Module 8: Using Reference-Type Variables 41
13. The CopyFileUpper.cs file should be as follows:
using System;
using System.IO;
class CopyFileUpper
{
static void Main( )
{
string sFrom, sTo;
StreamReader srFrom;
StreamWriter swTo;
// Prompt for input file name
Console.Write("Copy from:";
sFrom = Console.ReadLine( );
// Prompt for output file name
Console.Write("Copy to:";
sTo = Console.ReadLine( );
Console.WriteLine("Copy from {0} to {1}", sFrom,
êsTo);
try
{
srFrom = new StreamReader(sFrom);
swTo = new StreamWriter(sTo);
while (srFrom.Peek( )!=-1)
{
string sBuffer = srFrom.ReadLine( );
sBuffer = sBuffer.ToUpper( );
swTo.WriteLine(sBuffer);
}
swTo.Close( );
srFrom.Close( );
}
catch (FileNotFoundException)
{
Console.WriteLine("Input file not found";
}
catch (Exception e)
{
Console.WriteLine("Unexpected exception";
Console.WriteLine(e.ToString( ));
}
}
}
14. Save your work. Compile the project and correct any errors.

使用道具 举报

回复

您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

TOP技术积分榜 社区积分榜 徽章 团队 统计 知识索引树 积分竞拍 文本模式 帮助
  ITPUB首页 | ITPUB论坛 | 数据库技术 | 企业信息化 | 开发技术 | 微软技术 | 软件工程与项目管理 | IBM技术园地 | 行业纵向讨论 | IT招聘 | IT文档
  ChinaUnix | ChinaUnix博客 | ChinaUnix论坛
CopyRight 1999-2011 itpub.net All Right Reserved. 北京盛拓优讯信息技术有限公司版权所有 联系我们 未成年人举报专区 
京ICP备16024965号-8  北京市公安局海淀分局网监中心备案编号:11010802021510 广播电视节目制作经营许可证:编号(京)字第1149号
  
快速回复 返回顶部 返回列表