楼主: 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
51#
 楼主| 发表于 2006-8-13 21:18 | 只看该作者
32 Module 5: Methods and Parameters
The C# compiler finds two methods called Add in the class, and two method
calls to methods called Add within Main. Although the method names are the
same, the compiler can distinguish between the two Add methods by
comparing the parameter lists.
The first Add method takes two parameters, both of type int. The second Add
method takes three parameters, also of type int. Because the parameter lists are
different, the compiler allows both methods to be defined within the same class.
The first statement within Main includes a call to Add with two int parameters,
so the compiler translates this as a call to the first Add method. The second call
to Add takes three int parameters, so the compiler translates this as a call to the
second Add method.
You cannot share names among methods and variables, constants, or
enumerated types in the same class. The following code will not compile
because the name k has been used for both a method and a class variable:
class BadMethodNames
{
static int k;
static void k( ) {
// ...
}
}
Module 5: Methods and Parameters 33
Method Signatures
n Method Signatures Must Be Unique Within a Class
n Signature Definition
n Name of method
n Parameter type
n Parameter modifier
n Name of method
n Parameter type
n Parameter modifier
Forms Signature
Definition
Forrmss Siignaatturree
Definiittiioonn
n Name of parameter
n Return type of method
n Name of parameter
n Return type of method
No Effect on
Signature
No Effffeecctt on
Signattuurree
The C# compiler uses signatures to distinguish between methods in a class. In
each class, the signature of each method must differ from the signatures of all
other methods that are declared in that class.
Signature Definition
The signature of a method consists of the name of the method, the number of
parameters that the method takes, and the type and modifier (such as out or ref)
of each parameter.
The following three methods have different signatures, so they can be declared
in the same class.
static int LastErrorCode( )
{
}
static int LastErrorCode(int n)
{
}
static int LastErrorCode(int n, int p)
{
}
34 Module 5: Methods and Parameters
Elements That Do Not Affect the Signature
The method signature does not include the return type. The following two
methods have the same signatures, so they cannot be declared in the same class.
static int LastErrorCode(int n)
{
}
static string LastErrorCode(int n)
{
}
The method signature does not include the names of the parameters. The
following two methods have the same signature, even though the parameter
names are different.
static int LastErrorCode(int n)
{
}
static int LastErrorCode(int x)
{
}

使用道具 举报

回复
论坛徽章:
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
52#
 楼主| 发表于 2006-8-13 21:19 | 只看该作者
Module 5: Methods and Parameters 35
Using Overloaded Methods
n Consider Using Overloaded Methods When:
l You have similar methods that require different
parameters
l You want to add new functionality to existing code
n Do Not Overuse Because:
l Hard to debug
l Hard to maintain
Overloaded methods are useful when you have two similar methods that require
different numbers or types of parameters.
Similar Methods That Require Different Parameters
Imagine that you have a class containing a method that sends a greeting
message to the user. Sometimes the user name is known, and sometimes it is
not. You could define two different methods called Greet and GreetUser, as
shown in the following code:
class GreetDemo
{
static void Greet( )
{
Console.WriteLine("Hello";
}
static void GreetUser(string Name)
{
Console.WriteLine("Hello" + Name);
}
static void Main( )
{
Greet( );
GreetUser("Alex";
}
}
36 Module 5: Methods and Parameters
This will work, but now the class has two methods that perform almost exactly
the same task but that have different names. You can rewrite this class with
method overloading as shown in the following code:
class GreetDemo
{
static void Greet( )
{
Console.WriteLine("Hello";
}
static void Greet(string Name)
{
Console.WriteLine("Hello" + Name);
}
static void Main( )
{
Greet( );
Greet("Alex";
}
}
Module 5: Methods and Parameters 37
Adding New Functionality to Existing Code
Method overloading is also useful when you want to add new features to an
existing application without making extensive changes to existing code. For
example, the previous code could be expanded by adding another method that
greets a user with a particular greeting, depending on the time of day, as shown
in the following code:
class GreetDemo
{
enum TimeOfDay { Morning, Afternoon, Evening }
static void Greet( )
{
Console.WriteLine("Hello";
}
static void Greet(string Name)
{
Console.WriteLine("Hello" + Name);
}
static void Greet(string Name, TimeOfDay td)
{
string Message;
switch(td)
{
case TimeOfDay.Morning:
Message="Good morning";
break;
case TimeOfDay.Afternoon:
Message="Good afternoon";
break;
case TimeOfDay.Evening:
Message="Good evening";
break;
}
Console.WriteLine(Message + " " + Name);
}
static void Main( )
{
Greet( );
Greet("Alex";
Greet("Sandra", TimeOfDay.Morning);
}
}
Determining When to Use Overloading
Overuse of method overloading can make classes hard to maintain and debug.
In general, only overload methods that have very closely related functions but
differ in the amount or type of data that they need.

使用道具 举报

回复
论坛徽章:
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
53#
 楼主| 发表于 2006-8-13 21:19 | 只看该作者
38 Module 5: Methods and Parameters
Lab 5: Creating and Using Methods
Objectives
After completing this lab, you will be able to:
n Create and call methods with and without parameters.
n Use various mechanisms for passing parameters.
Prerequisites
Before working on this lab, you should be familiar with the following:
n Creating and using variables
n C# statements
Estimated time to complete this lab: 30 minutes
Module 5: Methods and Parameters 39
Exercise 1
Using Parameters in Methods That Return Values
In this exercise, you will define and use input parameters in a method that
returns a value. You will also write a test framework to read two values from
the console and display the results.
You will create a class called Utils. In this class, you will create a method
called Greater. This method will take two integer parameters as input and will
return the value of the greater of the two.
To test the class, you will create another class called Test that prompts the user
for two numbers, then calls Utils.Greater to determine which number is the
greater of the two, and then prints the result.
? To create the Greater method
1. Open the Utils.sln project in the install folder\Labs\Lab05\Starter\Utility
folder.
This contains a namespace called Utils that contains a class also called Utils.
You will write the Greater method in this class.
2. Create the Greater method as follows:
a. Open the Utils class.
b. Add a public static method called Greater to the Utils class.
c. The method will take two int parameters, called a and b, which will be
passed by value. The method will return an int value representing the
greater of the two numbers.
40 Module 5: Methods and Parameters
The code for the Utils class should be as follows:
namespace Utils
{
using System;
class Utils
{
//
// Return the greater of two integer values
//
public static int Greater(int a, int b)
{
if (a > b)
return a;
else
return b;
}
}
}
? To test the Greater method
1. Open the Test class.
2. Within the Main method, write the following code.
a. Define two integer variables called x and y.
b. Add statements that read two integers from keyboard input and use them
to populate x and y. Use the Console.ReadLine and int.Parse methods
that were presented in earlier modules.
c. Define another integer called greater.
d. Test the Greater method by calling it, and assign the returned value to
the variable greater.
3. Write code to display the greater of the two integers by using
Console.WriteLine .
Module 5: Methods and Parameters 41
The code for the Test class should be as follows:
namespace Utils
{
using System;
/// <summary>
/// This the test harness
/// </summary>
public class Test
{
public static void Main( )
{
int x; // Input value 1
int y; // Input value 2
int greater; // Result from Greater( )
// Get input numbers
Console.WriteLine("Enter first number:";
x = int.Parse(Console.ReadLine( ));
Console.WriteLine("Enter second number:";
y = int.Parse(Console.ReadLine( ));
// Test the Greater( ) method
greater = Utils.Greater(x,y);
Console.WriteLine("The greater value is "+
ê greater);
}
}
}
4. Save your work.
5. 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
54#
 楼主| 发表于 2006-8-13 21:19 | 只看该作者
42 Module 5: Methods and Parameters
Exercise 2
Using Methods with Reference Parameters
In this exercise, you will write a method called Swap that will exchange the
values of its parameters. You will use parameters that are passed by reference.
? To create the Swap method
1. Open the Utils.sln project in the install folder\Labs\Lab05\Starter\Utility
folder, if it is not already open.
2. Add the Swap method to the Utils class as follows:
a. Add a public static void method called Swap.
b. Swap will take two int parameters called a and b, which will be passed
by reference.
c. Write statements inside the body of Swap that exchange the values of a
and b. You will need to create a local int variable in Swap to
temporarily hold one of the values during the exchange. Name this
variable temp.
The code for the Utils class should be as follows:
namespace Utils
{
using System;
public class Utils
{
... existing code omitted for clarity ...
//
// Exchange two integers, passed by reference
//
public static void Swap(ref int a, ref int b)
{
int temp = a;
a = b;
b = temp;
}
}
}
Module 5: Methods and Parameters 43
? To test the Swap method
1. Edit the Main method in the Test class by performing the following steps:
a. Populate integer variables x and y.
b. Call the Swap method, passing these values as parameters.
Display the new values of the two integers before and after exchanging
them. The code for the Test class should be as follows:
namespace Utils
{
using System;
public class Test
{
public static void Main( )
{
... existing code omitted for clarity ...
// Test the Swap method
Console.WriteLine("Before swap: " + x + "," + y);
Utils.Swap(ref x,ref y);
Console.WriteLine("After swap: " + x + "," + y);
}
}
}
2. Save your work.
3. Compile the project, correcting any errors you find. Run and test the
program.
If the parameters were not exchanged as you expected, check to ensure
that you passed them as ref parameters.
Tip
44 Module 5: Methods and Parameters
Exercise 3
Using Methods with Output Parameters
In this exercise, you will define and use a static method with an output
parameter.
You will write a new method called Factorial that takes an int value and
calculates its factorial. The factorial of a number is the product of all the
numbers between 1 and that number. The factorial of zero is defined to be 1.
The following are examples of factorials:
n Factorial(0) = 1
n Factorial(1) = 1
n Factorial(2) = 1 * 2 = 2
n Factorial(3) = 1 * 2 * 3 = 6
n Factorial(4) = 1 * 2 * 3 * 4 = 24
? To create the Factorial method
1. Open the Utils.sln project in the install folder\Labs\Lab05\Starter\Utility
folder, if it is not already open.
2. Add the Factorial method to the Utils class, as follows:
a. Add a new public static method called Factorial.
b. This method will take two parameters called n and answer. The first,
passed by value, is an int value for which the factorial is to be calculated.
The second parameter is an out int parameter that will be used to return
the result.
c. The Factorial method should return a bool value that indicates whether
the method succeeded. (It could overflow and raise an exception.)
3. Add functionality to the Factorial method.
The easiest way to calculate a factorial is by using a loop. Perform the
following steps to add functionality to the method:
a. Create an int variable called k in the Factorial method. This will be
used as a loop counter.
b. Create another int variable called f, which will be used as a working
value inside the loop. Initialize the working variable f with the value 1.
c. Use a for loop to perform the iteration. Start with a value of 2 for k, and
finish when k reaches the value of parameter n. Increment k each time
the loop is performed.
d. In the body of the loop, multiply f successively by each value of k,
storing the result in f.
e. Factorial results can be very large even for small input values, so ensure
that all the integer calculations are in a checked block, and that you have
caught exceptions such as arithmetic overflow.
f. Assign the result value in f to the out parameter answer.
g. Return true from the method if the calculation is successful, and false if
the calculation is not successful (that is, if an exception occurs).
Module 5: Methods and Parameters 45
The code for the Utils class should be as follows:
namespace Utils
{
using System;
public class Utils
{
... existing code omitted for clarity ...
//
// Calculate factorial
// and return the result as an out parameter
//
public static bool Factorial(int n, out int answer)
{
int k; // Loop counter
int f; // Working value
bool ok=true; // True if okay, false if not
// Check the input value
if (n<0)
ok = false;
// Calculate the factorial value as the
// product of all of the numbers from 2 to n
try
{
checked
{
f = 1;
for (k=2; k<=n; ++k)
{
f = f * k;
}
}
}
catch(Exception)
{
// If something goes wrong in the calculation,
// catch it here. All exceptions
// are handled the same way: set the result
// to zero and return false.
(Code continued on following page.)

使用道具 举报

回复
论坛徽章:
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
55#
 楼主| 发表于 2006-8-13 21:19 | 只看该作者
46 Module 5: Methods and Parameters
f = 0;
ok = false;
}
// Assign result value
answer = f;
// Return to caller
return ok;
}
}
}
Module 5: Methods and Parameters 47
? To test the Factorial method
1. Edit the Test class as follows:
a. Declare a bool variable called ok to hold the true or false result.
b. Declare an int variable called f to hold the factorial result.
c. Request an integer from the user. Assign the input value to the int
variable x.
d. Call the Factorial method, passing x as the first parameter and f as the
second parameter. Return the result in ok.
e. If ok is true , display the values of x and f; otherwise, display a message
indicating that an error has occurred.
The code for the Test class should be as follows:
namespace Utils
{
public class Test
{
static void Main( )
{
int f; // Factorial result
bool ok; // Factorial success or failure
... existing code omitted for clarity ...
// Get input for factorial
Console.WriteLine("Number for factorial:";
x = int.Parse(Console.ReadLine( ));
// Test the factorial function
ok = Utils.Factorial(x, out f);
// Output factorial results
if (ok)
Console.WriteLine("Factorial(" + x + " = " +
f);
else
Console.WriteLine("Cannot compute this
êfactorial";
}
}
}
2. Save your work.
3. Compile the program, correct any errors, and then run and test the program.
48 Module 5: Methods and Parameters
If Time Permits
Implementing a Method by Using Recursion
In this exercise, you will re-implement the Factorial method that you created in
Exercise 3 by using recursion rather than a loop.
The factorial of a number can be defined recursively as follows: the factorial of
zero is 1, and you can find the factorial of any larger integer by multiplying that
integer with the factorial of the previous number. In summary:
If n=0, then Factorial(n) = 1; otherwise it is n * Factorial(n-1)
? To modify the existing Factorial method
1. Edit the Utils class and modify the existing Factorial method so that it uses
recursion rather than iteration.
The parameters and return types will be the same, but the internal
functionality of the method will be different. If you want to keep your
existing solution to Exercise 3, you will need to use another name for this
method.
2. Use the pseudocode shown above to implement the body of the Factorial
method. (You will need to convert it into C# syntax.)
3. Add code to the Test class to test your new method.
4. Save your work.
5. Compile the program, correct any errors, and then run and test the program.
Module 5: Methods and Parameters 49
The recursive version of the Factorial method (RecursiveFactorial) is
shown below:
//
// Another way to solve the factorial problem,
// this time as a recursive function
//
public static bool RecursiveFactorial(int n, out int f)
{
bool ok=true;
// Trap negative inputs
if (n<0)
{
f=0;
ok = false;
}
if (n<=1)
f=1;
else
{
try
{
int pf;
checked
{
ok = RecursiveFactorial(n-1,out pf);
f = n * pf;
}
}
catch(Exception)
{
// Something went wrong. Set error
// flag and return zero.
f=0;
ok=false;
}
}
return ok;
}

50 Module 5: Methods and Parameters
Review
n Using Methods
n Using Parameters
n Using Overloaded Methods
1. Explain what methods are and why they are important.
2. List the three ways in which data can be passed in parameters, and the
associated C# keywords.
3. When are local variables created and destroyed?
4. What keyword should be added to a method definition if the method needs
to be called from another class?
Module 5: Methods and Parameters 51
5. What parts of a method are used to form the signature?
6. Define the signature of a static method called Rotate that does not return a
value but that must “right rotate” its three integer parameters.
THIS PAGE INTENTIONALLY LEFT BLANK

使用道具 举报

回复
论坛徽章:
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
56#
 楼主| 发表于 2006-8-13 21:20 | 只看该作者
Contents
Overview 1
Overview of Arrays 2
Creating Arrays 11
Using Arrays 18
Lab 6: Creating and Using Arrays 31
Review 42
Module 6: Arrays
This course is based on the prerelease Beta 1 version of Microsoft? Visual Studio .NET.
Content in the final release of the course may be different from the content included in
this prerelease version. All labs in the course are to be completed with the Beta 1 version
of Visual Studio .NET.
Information in this document is subject to change without notice. The names of companies,
products, people, characters, and/or data mentioned herein are fictitious and are in no way intended
to represent any real individual, company, product, or event, unless otherwise noted. Complying
with all applicable copyright laws is the responsibility of the user. No part of this document may
be reproduced or transmitted in any form or by any means, electronic or mechanical, for any
purpose, without the express written permission of Microsoft Corporation. If, however, your only
means of access is electronic, permission to print one copy is hereby granted.
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.
ó 2001 Microsoft Corporation. All rights reserved.
Microsoft, ActiveX, BizTalk, IntelliSense, JScript, Microsoft Press, MSDN, PowerPoint, Visual
Basic, Visual C++, Visual C#, Visual Studio, Windows, Windows NT, and Windows Media are
either registered trademarks or trademarks of Microsoft Corporation in the U.S.A. and/or other
countries.
Other product and company names mentioned herein may be the trademarks of their respective
owners.
Module 6: Arrays 1
Overview
n Overview of Arrays
n Creating Arrays
n Using Arrays
Arrays provide an important means for grouping data. To make the most of C#,
it is important to understand how to use and create arrays effectively.
After completing this module, you will be able to:
n Create, initialize, and use arrays of varying rank.
n Use command-line arguments in a C# program.
n Understand the relationship between an array variable and an array instance.
n Use arrays as parameters for methods.
n Return arrays from methods.
2 Module 6: Arrays
u Overview of Arrays
n What Is an Array?
n Array Notation in C#
n Array Rank
n Accessing Array Elements
n Checking Array Bounds
n Comparing Arrays to Collections
This section provides an overview of general array concepts, introduces the key
syntax used to declare arrays in C#, and describes basic array features such as
rank and elements. In the next section, you will learn how to define and use
arrays.
Module 6: Arrays 3
What Is an Array?
n An Array Is a Sequence of Elements
l All elements in an array have the same type
l Structs can have elements of different types
l Individual elements are accessed using integer indexes
Integer index 0
(zero)
Integer index 4
(four)
There are two fundamental ways to group related data: structures (structs) and
arrays.
n Structures are groups of related data that have different types.
For example, a name (string), age (int), and gender (enum) naturally group
together in a struct that describes a person. You can access the individual
members of a struct by using their field names.
n Arrays are sequences of data of the same type.
For example, a sequence of houses naturally group together to form a street.
You can access an individual element of an array by using its integer
position, which is called an index.
Arrays allow random access. The elements of an array are located in contiguous
memory. This means a program can access all array elements equally quickly.
4 Module 6: Arrays
Array Notation in C#
n You Declare an Array Variable by Specifying:
l The element type of the array
l The rank of the array
l The name of the variable
This specifies the rank of the array
This specifies the name of the array variable
This specifies the element type of the array
ttyyppee[[ ]] nnaammee;;
You use the same notation to declare an array that you would use to declare a
simple variable. First, specify the type, and then specify the name of the
variable followed by a semicolon. You declare the variable type as an array by
using square brackets. Many other programming languages, such as C and C++,
also use square brackets to declare an array. Other languages, like Microsoft?
Visual Basic?, use parentheses.
In C#, array notation is very similar to the notation used by C and C++,
although it differs in two subtle-but-important ways:
n You cannot write square brackets to the right of the name of the variable.
n You do not specify the size of the array when declaring an array variable.
The following are examples of allowed and disallowed notation in C#:
type[ ]name; // Allowed
type name[ ]; // Disallowed in C#
type[4] name; // Also disallowed in C#
Module 6: Arrays 5
Array Rank
n Rank Is Also Known as the Array Dimension
n The Number of Indexes Associated with Each Element
Rank 1: One-dimensional
Single index associates with
each long element
Rank 2: Two-dimensional
Two indexes associate with
each int element
lloonngg[[ ]] rrooww;; iinntt[[,,]] ggrriidd;;
To declare a one-dimensional array variable, you use unadorned square brackets
as shown on the slide. Such an array is also called an array of rank 1 because
one integer index associates with each element of the array.
To declare a two-dimensional array, you use a single comma inside the square
brackets, as shown on the slide. Such an array is called an array of rank 2
because two integer indexes associate with each element of the array. This
notation extends in the obvious way: each additional comma between the
square brackets increases the rank of the array by one.
You do not include the length of the dimensions in the declaration for an array
variable.

使用道具 举报

回复
论坛徽章:
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
57#
 楼主| 发表于 2006-8-13 21:20 | 只看该作者
6 Module 6: Arrays
Accessing Array Elements
n Supply an Integer Index for Each Rank
l Indexes are zero-based
333
2 22
1 11
long[ ] row;
...
row[3];
long[ ] row;
...
row[3];
int[,] grid;
...
grid[1,2];
int[,] grid;
...
grid[1,2];
To access array elements, you use a syntax that is similar to the syntax you use
to declare array variables—both use square brackets. This visual similarity
(which is deliberate and follows a trend popularized by C and C++) can be
confusing if you are not familiar with it. Therefore, it is important for you to be
able to distinguish between an array variable declaration and an array element
access expression.
To access an element inside an array of rank 1, use one integer index. To access
an element inside an array of rank 2, use two integer indexes separated by a
comma. This notation extends in the same way as the notation for declaring
variables. To access an element inside an array of rank n, use n integer indexes
separated by commas. Notice again that the syntax used in an array element
access expression mirrors the syntax that is used to declare variables.
Array indexes (for all ranks) start from zero. To access the first element inside a
row, use the expression
row[0]
rather than the expression
row[1]
Module 6: Arrays 7
Some programmers use the phrase “initial element” rather than “first element”
to try to avoid any potential confusion. Indexing from 0 means that the last
element of an array instance containing size elements is found at [size-1] and
not at [size]. Accidentally using [size] is a common off-by-one error, especially
for programmers used to a language that indexes from one, such as Visual Basic.
Although the technique is rarely used, it is possib le to create arrays that
have user-defined integer index lower bounds. For more information, search for
“Array.CreateInstance” in the.NET Framework SDK Help documents.
Note
8 Module 6: Arrays
Checking Array Bounds
n All Array Access Attempts Are Bounds Checked
l A bad index throws an IndexOutOfRangeException
l Use the Length property and the GetLength method
rrooww ggrriidd
rrooww..GGeettLLeennggtthh((00))====66
rrooww..LLeennggtthh====66
ggrriidd..GGeettLLeennggtthh((00))====22
ggrriidd..GGeettLLeennggtthh((11))====44
ggrriidd..LLeennggtthh====22**44
In C#, an array element access expression is automatically checked to ensure
that the index is valid. This implicit bounds check cannot be turned off. Bounds
checking is one of the ways of ensuring that C# is a type-safe language.
Even though array bounds are automatically checked, you should still make
sure that integer indexes are always in bounds. To do this, you should manually
check the index bounds, often using a for statement termination condition, as
follows:
for (int i = 0; i < row.Length; i++) {
Console.WriteLine(row);
}
The Length property is the total length of the array, regardless of the rank of
the array. To determine the length of a specific dimension, you can use the
GetLength method, as follows:
for (int r = 0; r < grid.GetLength(0); r++) {
for (int c = 0; c < grid.GetLength(1); c++) {
Console.WriteLine(grid[r,c]);
}
}
Module 6: Arrays 9
Comparing Arrays to Collections
n An Array Cannot Resize Itself When Full
l A collection class, such as ArrayList, can resize
n An Array Is Intended to Store Elements of One Type
l A collection is designed to store elements of
different types
n Elements Of An Array Cannot Have Read-Only
Access
l A collection can have read-only access
n In General, Arrays Are Faster but Less Flexible
l Collections are slightly slower but more flexible
The size of an array instance and the type of its elements are permanently fixed
when the array is created. To create an array that always contains exactly 42
elements of type int, use the following syntax:
int[ ] rigid = new int [ 42 ];
The array will never shrink or expand, and it will never contain anything other
than ints. Collections are more flexible; they can expand or contract as elements
are removed and added. Arrays are intended to hold elements of a single type,
but collections were designed to contain elements of many different types. You
can achieve this flexibility by using boxing, as follows:
ArrayList flexible = new ArrayList( );
flexible.Add("one"; // Add a string here
...
flexible.Add(99); // And an int here!
You cannot create an array instance with read-only elements. The following
code will not compile:
const int[ ] array = {0, 1, 2, 3};
The following code will compile, but will not result in read-only elements:
readonly int[ ] array = {4,2}; // Compiles :-)
array[0]++; // But so does this :-(

使用道具 举报

回复
论坛徽章:
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
58#
 楼主| 发表于 2006-8-13 21:21 | 只看该作者
10 Module 6: Arrays
When you use the readonly keyword on an array variable declaration, it affects
the array variable itself (in this code, the array), and not the elements of the
array instance (in this code, array[0] and array[1]). In other words, using
readonly on an array variable declaration makes it impossible to reassign
another array instance to that array variable:
readonly int[ ] array = {4,2}; // Compiles
array = new int[2]{4,2} // Fails to compile
However, you can create a read-only collection as follows:
ArrayList flexible = new ArrayList( );
...
ArrayList noWrite = ArrayList.ReadOnly(flexible);
noWrite[0] = 42; // Causes run-time exception
Module 6: Arrays 11
u Creating Arrays
n Creating Array Instances
n Initializing Array Elements
n Initializing Multidimensional Array Elements
n Creating a Computed Size Array
n Copying Array Variables
In this section, you will learn how to create array instances, how to explicitly
initialize array instance elements, and how to copy array variables.
12 Module 6: Arrays
Creating Array Instances
n Declaring an Array Variable Does Not Create an Array!
l You must use new to explicitly create the array instance
l Array elements have an implicit default value of zero
row
0 0 0 0
grid
0 0 0
0 0 0
Variable Instance
lloonngg[[ ]] rrooww == nneeww lloonngg[[44]];;
iinntt[[,,]] ggrriidd == nneeww iinntt[[22,,33]];;
Declaring an array variable does not actually create an array instance. This is
because arrays are reference types and not value types. You use the new
keyword to create an array instance, also referred to as an array creation
expression. You must specify the size of all rank lengths when creating an array
instance. The following code will result in a compile-time error:
long[ ] row = new long[ ]; // Not allowed
int[,] grid = new int[,]; // Not allowed
The C# compiler implicitly initializes each array element to a default value
dependent on the array element type: integer array elements are implicitly
initialized to 0, floating-point array elements are implicitly initialized to 0.0,
and Boolean array elements are implicitly initialized to False. In other words,
the C# code
long[ ] row = new long[4];
will execute the following code at run-time:
long[ ] row = new long[4];
row[0] = 0L;
row[1] = 0L;
row[2] = 0L;
row[3] = 0L;
Module 6: Arrays 13
The compiler always allocates arrays in contiguous memory, regardless of the
base type of the array and the number of dimensions. If you create an array with
an expression such as new int[2,3,4], it is conceptually 2 x 3 x 4, but the
underlying memory allocation is a single block of memory large enough to
contain 2*3*4 elements.
It is also possible to create array instances whose elements that are arrays. Such
arrays are called ragged arrays (as opposed to rectangular arrays), and are
beyond the scope of this course. The following code shows how to create a
ragged array with three elements, each of which is an array of ints. (Each array
has a default value of null.)
int[ ][ ] table = new int[3][ ];
14 Module 6: Arrays
Initializing Array Elements
n The Elements of an Array Can Be Explicitly Initialized
l You can use a convenient shorthand
row
0 1 2 3
Equivalent
lloonngg[[ ]] rrooww == nneeww lloonngg[[44]] {{00,, 11,, 22,, 33}};;
lloonngg[[ ]] rrooww == {{00,, 11,, 22,, 33}};;
You can use an array initializer to initialize the values of the array instance
elements. An array initializer is a sequence of expressions enclosed by curly
braces and separated by commas. Array initializers are executed from left to
right and may include method calls and complex expressions, as in the
following example:
int[ ] data = new int[4]{a, b( ), c*d, e( )+f( )};
You can also use array initializers to initialize arrays of structs:
struct Date { ... }
Date[ ] dates = new Date[2];
You can only use this convenient shorthand notation when you initialize an
array instance as part of an array variable declaration and not as part of an
ordinary assignment statement.
int[ ] data1 = new int[4]{0, 1, 2, 3}; // Allowed
int[ ] data2 = {0, 1, 2, 3}; // Allowed
data2 = new int[4]{0, 1, 2, 3}; // Allowed
data2 = {0, 1, 2, 4}; // Not allowed
When initializing arrays, you must explicitly initialize all array elements. It is
not possible to let trailing array elements revert back to their default value of
zero:
int[ ] data3 = new int[2]{}; // Not allowed
int[ ] data4 = new int[2]{42}; // Still not allowed
int[ ] data5 = new int[2]{42,42}; // Allowed

使用道具 举报

回复
论坛徽章:
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
59#
 楼主| 发表于 2006-8-13 21:21 | 只看该作者
Module 6: Arrays 15
Initializing Multidimensional Array Elements
n You Can Also Initialize Multidimensional Array Elements
l All elements must be specified
grid
5 4 3
2 1 0
Implicitly a new int[2,3] array
?
ü
int[,] grid = {
{5, 4, 3},
{2, 1, 0}
};
int[,] grid = {
{5, 4, 3},
{2, 1, 0}
};
int[,] grid = {
{5, 4, 3},
{2, 1 }
};
int[,] grid = {
{5, 4, 3},
{2, 1 }
};
You must explicitly initialize all array elements regardless of the array
dimension:
int[,] data = new int[2,3] { // Allowed
{42, 42, 42},
{42, 42, 42},
};
int[,] data = new int[2,3] { // Not allowed
{42, 42},
{42, 42, 42},
};
int[,] data = new int[2,3] { // Not allowed
{42},
{42, 42, 42},
};
16 Module 6: Arrays
Creating a Computed Size Array
n The Array Size Does Not Need to Be a Compile-Time
Constant
l Any valid integer expression will work
l Accessing elements is equally fast in all cases
Array size specified by compile-time integer constant:
Array size specified by run-time integer value:
lloonngg[[ ]] rrooww == nneeww lloonngg[[44]];;
string s = Console.ReadLine();
int size = int.Parse(s);
long[ ] row = new long[size];
string s = Console.ReadLine();
int size = int.Parse(s);
long[ ] row = new long[size];
You can create multidimensional arrays by using run-time expressions for the
length of each dimension, as shown in the following code:
System.Console.WriteLine("Enter number of rows : ";
string s1 = System.Console.ReadLine( );
int rows = int.Parse(s1);
System.Console.WriteLine("Enter number of columns: ";
string s2 = System.Console.ReadLine( );
int cols = int.Parse(s2);
...
int[,] matrix = new int[rows,cols];
Alternatively, you can use a mixture of compile-time constants and run-time
expressions:
System.Console.WriteLine("Enter number of rows: ";
string s1 = System.Console.ReadLine( );
int rows = int.Parse(s1);
...
int[,] matrix = new int[rows,4];
There is one minor restriction. You cannot use a run-time expression to specify
the size of an array in combination with array-initializers:
string s = System.Console.ReadLine( );
int size = int.Parse(s);
int[ ] data = new int[size]{0,1,2,3}; // Not allowed
Module 6: Arrays 17
Copying Array Variables
n Copying an Array Variable Copies Just the Array Variable
l It does not copy the array instance
l Two array variables can refer to the same array instance
copy
row
0 0 0 0
Variable Instance
long[ ] row = new long[4];
long[ ] copy = row;
...
row[0]++;
int value = copy[0];
Console.WriteLine(value);
long[ ] row = new long[4];
long[ ] copy = row;
...
row[0]++;
int value = copy[0];
Console.WriteLine(value);
When you copy an array variable, you do not get a full copy of the array
instance. Analyzing the code shown in the slide reveals what happens when an
array variable is copied.
The following statements declare array variables called copy and row that both
refer to the same array instance (of four longs).
long[ ] row = new long[4];
long[ ] copy = row;
The following statement increments the initial element of this array instance
from 0 to 1. Both array variables still refer to the same array instance, whose
initial element is now 1.
row[0]++;
The next statement initializes an int called value from copy[0], which is the
initial array element of the array instance referred to by copy.
int value = copy[0];
Since copy and row both refer to the same array instance, initializing the value
from row[0] has exactly the same effect.
The final statement writes out value (which is 1) to the console:
Console.WriteLine(value);

使用道具 举报

回复
论坛徽章:
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
60#
 楼主| 发表于 2006-8-13 21:21 | 只看该作者
18 Module 6: Arrays
u Using Arrays
n Array Properties
n Array Methods
n Returning Arrays from Methods
n Passing Arrays as Parameters
n Command-Line Arguments
n Demonstration: Arguments for Main
n Using Arrays with foreach
n Quiz: Spot the Bugs
In this section, you will learn how to use arrays and how to pass arrays as
parameters to methods.
You will learn about the rules that govern the default values of array instance
elements. Arrays implicitly inherit from the System.Array class, which
provides many properties and methods. You will learn about some of the
commonly used properties and methods. You will also learn how to use the
foreach statement to iterate through arrays. Finally, you will learn how to avoid
some common pitfalls.
Module 6: Arrays 19
Array Properties
row
0 0 0 0
grid
0 0 0
0 0 0
rrooww..RRaannkk
rrooww..LLeennggtthh
ggrriidd..RRaannkk
ggrriidd..LLeennggtthh
lloonngg[[ ]] rrooww == nneeww lloonngg[[44]];;
iinntt[[,,]] ggrriidd == nneeww iinntt[[22,,33]];;
222
444
111
666
The Rank property is a read-only integer value that specifies the dimension of
the array instance. For example, given the code
int[ ] one = new int[a];
int[,] two = new int[a,b];
int[,,] three = new int[a,b,c];
the resulting rank values are as follows:
one.Rank == 1
two.Rank == 2
three.Rank == 3
The Length property is a read-only integer value that specifies the total length
of the array instance. For example, given the same three array declarations
above, the resulting length values are:
one.Length == a
two.Length == a * b
three.Length == a * b * c
20 Module 6: Arrays
Array Methods
n Commonly Used Methods
l Sort – sorts the elements in an array of rank 1
l Clear – sets a range of elements to zero or null
l Clone – creates a copy of the array
l GetLength – returns the length of a given dimension
l IndexOf – returns the index of the first occurrence of a
value
The System.Array class (a class that all arrays implicitly support) provides
many methods that you can use when working with arrays. This topic describes
some of the most commonly used methods.
n Sort method
This method performs an in-place sort on an array provided as an argument.
You can use this method to sort arrays of structures and classes as long as
they support the IComparable interface.
int[ ] data = {4,6,3,8,9,3}; // Unsorted
System.Array.Sort(data); // Now sorted
n Clear method
This method resets a range of array elements to zero (for value types) or
null (for reference types), as shown:
int[ ] data = {4,6,3,8,9,3};
System.Array.Clear(data, 0, data.Length);

使用道具 举报

回复

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

本版积分规则 发表回复

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