楼主: 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
61#
 楼主| 发表于 2006-8-13 21:21 | 只看该作者
Module 6: Arrays 21
n Clone method
This method creates a new array instance whose elements are copies of the
elements of the cloned array. You can use this method to clone arrays of
user-defined structs and classes. Following is an example:
int[ ] data = {4,6,3,8,9,3};
int[ ] clone = (int [ ])data.Clone( );
The Clone method performs a shallow copy. If the array being
copied contains references to objects, the references will be copied and not
the objects; both arrays will refer to the same objects.
n GetLength method
This method returns the length of a dimension provided as an integer
argument. You can use this method for bounds -checking multidimensional
arrays. Following is an example:
int[,] data = { {0, 1, 2, 3}, {4, 5, 6, 7} };
int dim0 = data.GetLength(0); // == 2
int dim1 = data.GetLength(1); // == 4
n IndexOf method
This method returns the integer index of the first occurrence of a value
provided as an argument, or –1 if the value is not present. You can only use
this method on one-dimensional arrays. Following is an example:
int[ ] data = {4,6,3,8,9,3};
int where = System.Array.IndexOf(data, 9); // == 4
Depending on the type of the elements in the array, the IndexOf
method may require that you override the Equals method for the element
type. You will learn more about this in a later module.
Caution
Note
22 Module 6: Arrays
Returning Arrays from Methods
n You Can Declare Methods to Return Arrays
l Use the syntax of the familiar type name pattern
class Example {
static void Main( ) {
int[ ] array = CreateArray(42);
...
}
static int[ ] CreateArray(int size) {
int[ ] created = new int[size];
return created;
}
}
class Example {
static void Main( ) {
int[ ] array = CreateArray(42);
...
}
static int[ ] CreateArray(int size) {
int[ ] created = new int[size];
return created;
}
}
To declare an array variable, use the syntax of the familiar type name pattern.
For example, to create an array of ints, you would specify the type, int, on the
left, and the name variable on the right. For example, you can use the following
syntax to declare a simple array variable of ints:
int[ ] variable;
The following variable has been declared as type int[ ], which is then combined
with the [0]++ to form the rest of the expression:
variable[0]++
You also use the syntax of the type name pattern to declare a method that
returns an array. In the following example, the type, in this case int is on the
left and the method name is on the right:
int[ ] method( ){...}
In the following expression, method( ) has type int[ ], which is then combined
with the [0]++ to form the rest of the expression:
method( )[0]++
In the slide, the CreateArray method is implemented by using two statements.
You can combine these two statements into one return statement as follows:
static int[ ] CreateArray(int size) {
return new int[size];
}
Module 6: Arrays 23
C++ programmers should note that in both cases the size of the array that is
returned is not specified. If you specify the array size, you will get a compiletime
error, as in this example:
// Compiler error
static int[4] CreateArray( ) {
return new int[4];
}
You can also return arrays of rank greater than one, as shown in the following
example:
static int[,] CreateArray( ) {
string s1 = System.Console.ReadLine( );
int rows = int.Parse(s1);
string s2 = System.Console.ReadLine( );
int cols = int.Parse(s2);
return new int[rows,cols];
}

使用道具 举报

回复
论坛徽章:
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
62#
 楼主| 发表于 2006-8-13 21:21 | 只看该作者
24 Module 6: Arrays
Passing Arrays as Parameters
n An Array Parameter Is a Copy of the Array Variable
l Not a copy of the array instance
class Example2 {
static void Main( ) {
int[ ] arg = {10, 9, 8, 7};
Method(arg);
System.Console.WriteLine(arg[0]);
}
static void Method(int[ ] parameter) {
parameter[0]++;
}
}
class Example2 {
static void Main( ) {
int[ ] arg = {10, 9, 8, 7};
Method(arg);
System.Console.WriteLine(arg[0]);
}
static void Method(int[ ] parameter) {
parameter[0]++;
}
}
This method will modify
the original array
instance created in Main
This method will modify
the original array
instance created in Main
When you pass an array variable as an argument to a method, the method
parameter becomes a copy of the array variable argument. In other words, the
array parameter is initialized from the argument. You use the same syntax to
initialize the array parameter that you used to initialize an array variable, as
described earlier in the Copying Array Variables topic. The array argument and
the array parameter both refer to the same array instance.
In the code shown on the slide, arg is initialized with an array instance of
length 4 that contains the integers 10, 9, 8, and 7. Then arg is passed as the
argument to Method. Method accepts arg as a parameter, meaning that arg
and parameter both refer to the same array instance (the one used to initialize
arg). The expression parameter[0]++ inside Method then increments the
initial element in the same array instance from 10 to 11. (Since the initial
element of an array is accessed by specifying the index value 0 and not 1, it is
also referred to as the “zeroth” element.) Method then returns and Main writes
out the value of arg[0] to the console. The arg parameter still refers to the
same array instance, the zeroth element of which has just been incremented, so
11 is written to the console.
Because passing an array variable does not create a deep copy of the array
instance, passing an array as a parameter is very fast. If you want a method to
have write access to the argument’s array instance, this shallow copy behavior
is entirely appropriate.
The Array.Clone method is useful when you need to ensure that the called
method will not alter the array instance and you are willing to trade a longer
running time for this guarantee. You can also pass a newly created array as an
array parameter as follows:
Method(new int[4]{10, 9, 8, 7});
Module 6: Arrays 25
Command-Line Arguments
n The Runtime Passes Command Line Arguments to Main
l Main can take an array of strings as a parameter
l The name of the program is not a member of the array
class Example3 {
static void Main(string[ ] args) {
for (int i = 0; i < args.Length; i++) {
System.Console.WriteLine(args);
}
}
}
class Example3 {
static void Main(string[ ] args) {
for (int i = 0; i < args.Length; i++) {
System.Console.WriteLine(args);
}
}
}
When you run console-based programs, you often pass extra arguments on the
command line. For example, if you run pkzip at a command prompt, you can
add extra arguments to control the creation of .zip files. The following
command recursively adds all *.cs code files into code.zip:
C:\> pkzip –add –rec –path=relative c:\code *.cs
If you had written the pkzip program using C#, you would capture these
command-line arguments as an array of strings that the runtime would pass to
Main:
class PKZip {
static void Main(string[ ] args) {
...
}
}
In this example, when you run the pkzip command, the runtime would
effectively execute the following code:
string[ ] args = {
"-add",
"-rec",
"-path=relative",
"c:\\code",
"*.cs"
};
PKZip.Main(args);
Unlike in C and C++, the name of the program itself is not passed as
args[0] in C#.
Note

使用道具 举报

回复
论坛徽章:
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
63#
 楼主| 发表于 2006-8-13 21:22 | 只看该作者
26 Module 6: Arrays
Demonstration: Arguments for Main
In this demonstration, you will see how to pass command-line arguments to a
C# program.
Module 6: Arrays 27
Using Arrays with foreach
n The foreach Statement Abstracts Away Many Details of
Array Handling
class Example4 {
static void Main(string[ ] args) {
foreach (string arg in args) {
System.Console.WriteLine(arg);
}
}
}
class Example4 {
static void Main(string[ ] args) {
foreach (string arg in args) {
System.Console.WriteLine(arg);
}
}
}
When it is applicable, the foreach statement is useful because it abstracts the
mechanics of iterating through every element of an array. Without foreach, you
might write:
for (int i = 0; i < args.Length; i++) {
System.Console.WriteLine(args);
}
With foreach, you can write:
foreach (string arg in args) {
System.Console.WriteLine(arg);
}
Notice that when you use the foreach statement, you do not need or use:
n An integer index (int i)
n An array bounds check (i < args.Length)
n An array access expression (args)
You can also use the foreach statement to iterate through the elements in an
array of rank 2 or higher. For example, the following foreach statement will
write out the values 0, 1, 2, 3, 4, and 5:
int[,] numbers = { {0,1,2}, {3,4,5} };
foreach (int number in numbers) {
System.Console.WriteLine(number);
}
28 Module 6: Arrays
This page is intentionally blank.
Module 6: Arrays 29
Quiz: Spot the Bugs
222
333
444
555
111 int [ ] array;
array = {0, 2, 4, 6};
int [ ] array;
array = {0, 2, 4, 6};
int [ ] array;
System.Console.WriteLine(array[0]);
int [ ] array;
System.Console.WriteLine(array[0]);
int [ ] array = new int[3];
System.Console.WriteLine(array[3]);
int [ ] array = new int[3];
System.Console.WriteLine(array[3]);
iinntt [[ ]] aarrrraayy == nneeww iinntt[[ ]];;
iinntt [[ ]] aarrrraayy == nneeww iinntt[[33]]{{00,, 11,, 22,, 33}};;
In this quiz, you can work with a partner to spot the bugs in the code on the
slide. To see the answers to this quiz, turn the page.
30 Module 6: Arrays
Answers
These are the bugs that the students should be able to find:
1. An array initializer is used in an assignment without an array creation
expression. The shortcut int[ ] array = { … }; is only possible in an
array declaration. This bug will result in a compile-time error.
2. The array variable has been declared, but there is no array creation
expression, and hence there is no array instance. This bug will also result in
a compile-time error.
3. A classic off-by-one out-of-bounds error. The array has length three,
making valid index values 0, 1, and 2. Remember, arrays are indexed from
zero in C#. This bug will cause a System.IndexOutOfRange run-time
exception.
4. The length of the array is not specified in the array creation expression. The
length of an array must be specified when an array instance is created.
5. The number of array elements is specified as 3 in new int[3] however,
there are four integer literals in the array initializer.

使用道具 举报

回复
论坛徽章:
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
64#
 楼主| 发表于 2006-8-13 21:22 | 只看该作者
Module 6: Arrays 31
Lab 6: Creating and Using Arrays
Objectives
After completing this lab, you will be able to:
n Create and use arrays of value types.
n Pass arguments to Main.
n Create and use computed size arrays.
n Use arrays of multiple rank.
Prerequisites
Before working on this lab, you should be familiar with the following:
n Using C# programming statements.
n Writing and using methods in C#.
Estimated time to complete this lab: 60 minutes
32 Module 6: Arrays
Exercise 1
Working with an Array of Value Types
In this exercise, you will write a program that expects the name of a text file as
an argument to Main. The program will summarize the contents of the text file.
It will read the contents of the text file into an array of characters and then
iterate through the array, counting the number of vowels and consonants.
Finally, it will print the total number of characters, vowels, consonants, and
newlines to the console.
? To capture the name of the text file as a parameter to Main
1. Open the project FileDetails.sln. This project is in the install folder\
Labs\Lab06\Starter\FileDetails folder.
2. Add an array of strings called args as a parameter to the Main method of
the FileDetails class. This array will contain all of the command-line
arguments supplied when the program is run. This is how the runtime passes
command-line arguments to Main. In this exercise, the command-line
argument passed to Main will be the name of the text file.
3. Add a statement to Main that writes the length of args to the console. This
statement will verify that the length of args is zero when no command-line
arguments are passed to Main by the runtime.
4. Add a foreach statement to Main that writes each string in args to the
console. This statement will verify that Main receives the command-line
arguments from the runtime.
Your completed code should look as follows:
static void Main(string[ ] args)
{
Console.WriteLine(args.Length);
foreach (string arg in args) {
Console.WriteLine(arg);
}
}
5. Compile the FileDetails.cs program and correct any errors. Run the program
from the command line, supplying no command-line arguments. Verify that
the length of args is zero.
To run the program from the command line, open the Command
window and go to the install folder\Labs\Lab06\Starter\FileDetails\bin\
Debug folder. The executable file will be located in this folder.
6. Run the program from the command line, supplying the name of the
install folder\Labs\Lab06\Solution\FileDetails\FileDetails.cs file. Verify
that the runtime passes the file name to Main.
7. Test the program by supplying a variety of other command-line arguments,
and verify that each command-line argument is written to the console as
expected. Comment out the statements that write to the console.
8. Add a statement to Main that declares a string variable called filename and
initialize it with args[0].
Tip
Module 6: Arrays 33
? To read from the text file into an array
1. Remove the comment from the FileStream and StreamReader declaration
and initialization code.
2. Determine the length of the text file.
To locate an appropriate property of the Stream class, search for
“Stream class” in the .NET Framework SDK Help documents.
3. Add a statement to Main that declares a character array variable called
contents. Initialize contents with a new array instance whose length is equal
to the length of the text file, which you have just determined.
4. Add a for statement to Main. The body of the for statement will read a
single character from reader and add it to contents.
Use the Read method, which takes no parameters and returns an int.
Cast the result to a char before storing it in the array.
5. Add a foreach statement to Main that writes the whole character array to
the console character by character. This statement will verify that the text
file has been successfully read into the contents array.
Your completed code should look as follows:
static void Main(string[ ] args)
{
string fileName = args[0];
FileStream stream = new FileStream(fileName,
ê FileMode.Open);
StreamReader reader = new StreamReader(stream);
int size = (int)stream.Length;
char[ ] contents = new char[size];
for (int i = 0; i < size; i++) {
contents = (char)reader.Read( );
}
foreach(char ch in contents) {
Console.Write(ch); }
Console.WriteLine(args.Length);
foreach (string arg in args) {
Console.WriteLine(arg);
}
}
6. Compile the program and correct any errors. Run the program, supplying
the name of the install folder\Labs\Lab06\Solution\FileDetails\
FileDetails.cs file as a command-line argument. Verify that the contents of
the file are correctly written to the console.
7. Comment out the foreach statement.
8. Close the Reader object by calling the appropriate StreamReader method.

使用道具 举报

回复
论坛徽章:
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
65#
 楼主| 发表于 2006-8-13 21:23 | 只看该作者
34 Module 6: Arrays
To classify and summarize the contents of the file
1. Declare a new static method called Summarize in the FileDetails class.
This method will not return anything and will expect a character array
parameter. Add a statement to Main that calls the Summarize method,
passing contents as the argument.
2. Add a foreach statement to Summarize that inspects each character in the
array argument. Count the number of vowel, consonant, and newline
characters that occur, storing the results in separate variables.
To determine whether a character is a vowel, create a string containing
all possible vowels and use the IndexOf method on that string to determine
whether the character exists in that string, as follows:
if ("AEIOUaeiou".IndexOf(myCharacter) != -1) {
// myCharacter is a vowel
} else {
// myCharacter is not a vowel
}
3. Write four lines to the console that display:
· The total number of characters in the file.
· The total number of vowels in the file.
· The total number of consonants in the file.
· The total number of lines in the file.
Your completed code should look as follows:
static void Summarize(char[ ] contents)
{
int vowels = 0, consonants = 0, lines = 0;
foreach (char current in contents) {
if (Char.IsLetter(current)) {
if ("AEIOUaeiou".IndexOf(current) != -1) {
vowels++;
} else {
consonants++;
}
}
else if (current == '\n') {
lines++;
}
}
Console.WriteLine("Total no of characters: {0}",
êcontents.Length);
Console.WriteLine("Total no of vowels : {0}",
êvowels);
Console.WriteLine("Total no of consonants: {0}",
êconsonants);
Console.WriteLine("Total no of lines : {0}",
êlines);
}

Module 6: Arrays 35
4. Compile the program and correct any errors. Run the program from the
command line to summarize the contents of the solution file:
install folder\Labs\Lab06\Solution\FileDetails\FileDetails.cs. The correct
totals should be as follows:
· 1,401 characters
· 251 vowels
· 401 consonants
· 39 lines
36 Module 6: Arrays
Exercise 2
Mullying Matrices
In this exercise, you will write a program that uses arrays to mully matrices
together. The program will read four integer values from the console and store
them in a 2 x 2 integer matrix. It will then read another four integer values from
the console and store them in a second 2 x 2 integer matrix. The program will
then mully the two matrices together, storing the result in a third 2 x 2 integer
matrix. Finally, it will print the resulting matrix to the console.
The formula for mullying two matrices—A and B—together is as follows:
A1 A2 B1 B2 A1.B1 + A2.B3 A1.B2 + A2.B4
A3 A4 B3 B4 A3.B1 + A4.B3 A3.B2 + A4.B4
To mully two matrices together
1. Open the project MatrixMully.sln in the install folder\
Labs\Lab06\Starter\MatrixMully folder.
2. In the MatrixMully class, add a statement to Main that declares a 2 x 2
array of ints and names the array a. The final solution for the program will
read the values of a from the console. For now, initialize a with the integer
values in the following table. (This is to help verify that the mullication is
performed correctly and that the subsequent refactoring retains the intended
behavior.)
1 2
3 4
3. Add a statement to Main that declares a 2 x 2 array of ints and names the
array b. The final solution for the program will read the values of b from the
console. For now, initialize b with the integer values shown in the following
table:
5 6
7 8
4. Add a statement to Main that declares a 2 x 2 array of ints and names the
array result. Initialize result by using the following cell formulae:
a[0,0] * b[0,0] + a[0,1] * b[1,0] a[0,0] * b[0,1] + a[0,1] * b[1,1]
a[1,0] * b[0,0] + a[1,1] * b[1,0] a[1,0] * b[0,1] + a[1,1] * b[1,1]
5. Add four statements to Main that write the four int values in result to the
console. These statements will help you to check that you have copied the
formulae correctly.

使用道具 举报

回复
论坛徽章:
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
66#
 楼主| 发表于 2006-8-13 21:23 | 只看该作者
Module 6: Arrays 37
Your completed code should look as follows:
static void Main( )
{
int[,] a = new int[2,2];
a[0,0] = 1; a[0,1] = 2;
a[1,0] = 3; a[1,1] = 4;
int[,] b = new int[2,2];
b[0,0] = 5; b[0,1] = 6;
b[1,0] = 7; b[1,1] = 8;
int[,] result = new int[2,2];
result[0,0]=a[0,0]*b[0,0] + a[0,1]*b[1,0];
result[0,1]=a[0,0]*b[0,1] + a[0,1]*b[1,1];
result[1,0]=a[1,0]*b[0,0] + a[1,1]*b[1,0];
result[1,1]=a[1,0]*b[0,1] + a[1,1]*b[1,1];
Console.WriteLine(result[0,0]);
Console.WriteLine(result[0,1]);
Console.WriteLine(result[1,0]);
Console.WriteLine(result[1,1]);
}
6. Compile the program and correct any errors. Run the program. Verify that
the four values in result are as follows:
19 22
43 50
To output the result by using a method with an array parameter
1. Declare a new static method called Output in the MatrixMully class.
This method will not return anything and will expect an int array of rank 2
as a parameter called result.
2. Cut from Main the four statements that write the four values of result to the
console and paste them into Output.
3. Add a statement to Main that calls the Output method, passing result as
the argument. (This should replace the code that was cut in the previous
step.)
Your completed code should look as follows:
static void Output(int[,] result)
{
Console.WriteLine(result[0,0]);
Console.WriteLine(result[0,1]);
Console.WriteLine(result[1,0]);
Console.WriteLine(result[1,1]);
}
38 Module 6: Arrays
4. Compile the program and correct any errors. Run the program. Verify that
the four values written to the console are still as follows:
19 22
43 50
5. Refactor the Output method to use two nested for statements instead of
four WriteLine statements. Use the literal value 2 in both array bounds
checks.
Your completed code should look as follows:
static void Output(int[,] result)
{
for (int r = 0; r < 2; r++) {
for (int c = 0; c < 2; c++) {
Console.Write("{0} ", result[r,c]);
}
Console.WriteLine( );
}
}
6. Compile the program and correct any errors. Run the program. Verify that
the four values written to the console are still as follows:
19 22
43 50
7. Modify the Output method again, to make it more generic. Replace the
literal value 2 in the array bounds checks with calls to the GetLength
method of each.
Your completed code should look as follows:
static void Output(int[,] result)
{
for (int r = 0; r < result.GetLength(0); r++) {
for (int c = 0; c < result.GetLength(1); c++) {
Console.Write("{0} ", result[r,c]);
}
Console.WriteLine( );
}
}
8. Compile the program and correct any errors. Run the program. Verify that
the four values written to the console are still as follows:
19 22
43 50

使用道具 举报

回复
论坛徽章:
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
67#
 楼主| 发表于 2006-8-13 21:23 | 只看该作者
Module 6: Arrays 39
To calculate result in a method and return it
1. Declare a new static method called Mully inside the MatrixMully
class. This method will return an int array of rank 2 and will expect two int
arrays of rank 2, named a and b, as parameters.
2. Copy (but do not cut) the declaration and initialization of result from Main
into Mully.
3. Add a return statement to Mully that returns result.
4. Replace the initialization of result in Main with a call to Mully, passing
a and b as arguments.
Your completed code should look as follows:
static int[,] Mully(int[,] a, int [,] b)
{
int[,] result = new int[2,2];
result[0,0]=a[0,0]*b[0,0] + a[0,1]*b[1,0];
result[0,1]=a[0,0]*b[0,1] + a[0,1]*b[1,1];
result[1,0]=a[1,0]*b[0,0] + a[1,1]*b[1,0];
result[1,1]=a[1,0]*b[0,1] + a[1,1]*b[1,1];
return result;
}
5. Compile the program, and correct any errors. Run the program. Verify that
the four values written to the console are still as follows:
19 22
43 50
To calculate result in a method by using for statements
1. Replace the initialization of result in Mully with a newly created 2 x 2
array of ints.
2. Add two nested for statements to Mully. Use an integer called r in the
outer for statement to it erate through each index of the first dimension of
result . Use an integer called c in the inner for statement to iterate through
each index of the second dimension of result. Use the literal value 2 directly
in both array bounds checks. The body of the inner for statement will need
to calculate and set the value of result[r,c] by using the following
formula:
result[r,c] = a[r,0] * b[0,c]
+ a[r,1] * b[1,c]
Your completed code should look like this:
static int[,] Mully(int[,] a, int [,] b)
{
int[,] result = new int[2,2];
for (int r = 0; r < 2; r++) {
for (int c = 0; c < 2; c++) {
result[r,c] += a[r,0] * b[0,c] + a[r,1] * b[1,c];
}
}
return result;
}
40 Module 6: Arrays
3. Compile the program and correct any errors. Run the program. Verify that
the four values written to the console are still as follows:
19 22
43 50
To input the first matrix from the console
1. Replace the initialization of a in Main with a newly created 2 x 2 array of
ints.
2. Add statements to Main that prompt the user and read four values into a
from the console. These statements should be placed before invoking the
Mully method. The statements to read one value from the console are:
string s = Console.ReadLine( );
a[0,0] = int.Parse(s);
3. Compile the program and correct any errors. Run the program, entering the
same four values for a from the console (that is, 1, 2, 3, and 4). Verify that
the four values written to the console are still as follows:
19 22
43 50
4. Declare a new static method called Input inside the MatrixMully class.
This method will not return anything and will expect an int array of rank 2
as a parameter called a.
5. Cut the statements that read four values into a from Main and paste them
into Input. Add a statement to Main that calls Input, passing in a as the
parameter. This should be placed before the call to Mully.
6. Compile the program and correct any errors. Run the program, entering the
same four values for a from the console (that is, 1, 2, 3, and 4). Verify that
the four values written to the console are still as follows:
19 22
43 50
7. Change the Input method to use two nested for statements. Use the literal
value 2 directly in both array bounds checks. Include a Write statement
inside the Input method that prompts the user for each input.

使用道具 举报

回复
论坛徽章:
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
68#
 楼主| 发表于 2006-8-13 21:23 | 只看该作者
Module 6: Arrays 41
Your completed code should look as follows:
static void Input(int[,] a)
{
for (int r = 0; r < 2; r++) {
for (int c = 0; c < 2; c++) {
Console.Write(
ê"Enter value for [{0},{1}] : ", r, c);
string s = Console.ReadLine( );
a[r,c] = int.Parse(s);
}
}
Console.WriteLine( );
}
8. Compile the program and correct any errors. Run the program, entering the
same four values for a from the console (that is, 1, 2, 3, and 4). Verify that
the four values written to the console are still as follows:
19 22
43 50
To input the second matrix from the console
1. Replace the initialization of b in Main with a newly created 2 x 2 array of
ints whose four values all default to zero.
2. Add a statement to Main that reads values into b from the console by
calling the Input method and passing b as the argument.
3. Compile the program and correct any errors. Run the program, entering the
same four values for a (1, 2, 3, and 4) and the same four values for b (5, 6, 7,
and 8). Verify that the four values written to the console are still as follows:
19 22
43 50
4. Run the program with different data. Collaborate with a fellow student to
see whether you get the same answer for the same input.
42 Module 6: Arrays
Review
n Overview of Arrays
n Creating Arrays
n Using Arrays
1. Declare an array of ints of rank 1 called evens, and initialize it with the first
five even numbers, starting with zero.
2. Write a statement that declares variable called crowd of type int, and
initialize it with the second element of evens. Remember, the second
element does not reside at index 2 because array indexes do not start at 1.
3. Write two statements. The first will declare an array of ints of rank 1 called
copy; the second will assign to copy from evens.
Module 6: Arrays 43
4. Write a static method called Method that returns an array of ints of rank 2
and expects no arguments. The body of Method will contain a single return
statement. This statement returns a newly created array of rank 2 with
dimensions 3 and 5 whose 15 elements are all initialized to 42.
5. Write a static method called Parameter that returns nothing and expects a
two-dimensional array as its single argument. The body of the method will
contain two WriteLine statements that write the length of each dimension
to the console.
6. Write a foreach statement that iterates over a one-dimensional array of
strings called names, writing each name to the console.
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
69#
 楼主| 发表于 2006-8-13 21:24 | 只看该作者
Contents
Overview 1
Classes and Objects 2
Using Encapsulation 10
C# and Object Orientation 21
Lab 7: Creating and Using Classes 39
Defining Object-Oriented Systems 53
Review 62
Module 7: Essentials of
Object-Oriented
Programming
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 otherwi se 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, 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 7: Essentials of Object-Oriented Programming 1
Overview
n Classes and Objects
n Using Encapsulation
n C# and Object Orientation
n Defining Object-Oriented Systems
C# is an object-oriented programming language. In this section, you will learn
the terminology and concepts required to create and use classes in C#.
After completing this module, you will be able to:
n Define the terms object and class in the context of object-oriented
programming.
n Define the three core aspects of an object: identity, state, and behavior.
n Describe abstraction and how it helps you to create reusable classes that are
easy to maintain.
n Use encapsulation to combine methods and data in a single class.
n Explain the concepts of inheritance and polymorphism.
n Create and use classes in C#.
2 Module 7: Essentials of Object-Oriented Programming
u Classes and Objects
n What Is a Class?
n What Is an Object?
n Comparing Classes to Structs
n Abstraction
The whole structure of C# is based on the object-oriented programming model.
To make the most effective use of C# as a language, you need to understand the
nature of object-oriented programming.
In this section, you will learn about the basics of object-oriented programming.
You will examine classes and objects in the context of object-oriented
programming. You will then learn the how to apply the concept of abstraction.
Module 7: Essentials of Object-Oriented Programming 3
What Is a Class?
n For the Philosopher…
l An artefact of human classification!
l Classify based on common behavior or attributes
l Agree on descriptions and names of useful classes
l Create vocabulary; we communicate; we think!
n For the Object-Oriented Programmer…
l A named syntactic construct that describes common
behavior and attributes
l A data structure that includes both data and functions
CAR?
The root word of classification is class. Forming classes is an act of
classification, and it is something that all human beings (not just programmers)
do. For example, all cars share common behavior (they can be steered, stopped,
and so on) and common attributes (they have four wheels, an engine, and so on).
You use the word car to refer to all of these common behaviors and properties.
Imagine what it would be like if you were not able to classify common
behaviors and properties into named concepts! Instead of saying car, you would
have to say all the things that car means. Sentences would be long and
cumbersome. In fact, communication would probably not be possible at all. As
long as everyone agrees what a word means, that is, as long as we all speak the
same language, communication works well—we can express complex but
precise ideas in a compact form. We then use these named concepts to form
higher-level concepts and to increase the expressive power of communication.
All programming languages can describe common data and common functions.
This ability to describe common features helps to avoid duplication. A key
motto in programming is “Don’t repeat yourself.” Duplicate code is
troublesome because it is more difficult to maintain. Code that does not repeat
itself is easier to maintain, partly because there is just less of it! Object-oriented
languages take this concept to the next level by allowing descriptions of classes
(sets of objects) that share structure and behavior. If done properly, this
paradigm works extremely well and fits naturally into the way people think and
communicate.
Classes are not restricted to classifying concrete objects (such as cars); they can
also be used to classify abstract concepts (such as time). However, when you
are classifying abstract concepts, the boundaries are less clear, and good design
becomes more important.
The only real requirement for a class is that it helps people communicate.

使用道具 举报

回复
论坛徽章:
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
70#
 楼主| 发表于 2006-8-13 21:24 | 只看该作者
4 Module 7: Essentials of Object-Oriented Programming
What Is an Object?
n An Object Is an Instance of a Class
n Objects Exhibit
l Identity: Objects are distinguishable from one another
l Behavior: Objects can perform tasks
l State: Objects store information
The word car means different things in different contexts. Sometimes we use
the word car to refer to the general concept of a car: we speak of car as a class,
meaning the set of all cars, and do not have a specific car in mind. At other
times we use the word car to mean a specific car. Programmers use the term
object or instance to refer to a specific car. It is important to understand this
difference.
The three characteristics of identity, behavior, and state form a useful way to
think about and understand objects.
Identity
Identity is the characteristic that distinguishes one object from all other objects
of the same class. For example, imagine that two neighbors own a car of exactly
the same make, model, and color. Despite the obvious similarities, the
registration numbers are guaranteed to be unique and are an outward reflection
that cars exhibit identity. The law determines that it is necessary to distinguish
one car object from another. (How would car insurance work without car
identity?)
Module 7: Essentials of Object-Oriented Programming 5
Behavior
Behavior is the characteristic that makes objects useful. Objects exist in order to
provide behavior. Most of the time you ignore the workings of the car and think
about its high-level behavior. Cars are useful because you can drive them. The
workings exist but are mostly inaccessible. It is the behavior of an object that is
accessible. The behavior of an object also most powerfully determines its
classification. Objects of the same class share the same behavior. A car is a car
because you can drive it; a pen is a pen because you can write with it.
State
State refers to the inner workings of an object that enable it to provide its
defining behavior. A well-designed object keeps its state inaccessible. This is
closely linked to the concepts of abstraction and encapsulation. You do not care
how an object does what it does; you just care that it does it. Two objects may
coincidentally contain the same state but nevertheless be two different objects.
For example, two identical twins contain exactly the same state (their DNA) but
are two distinct people.
6 Module 7: Essentials of Object-Oriented Programming
Comparing Classes to Structs
n A Struct Is a Blueprint for a Value
l No identity, accessible state, no added behavior
n A Class Is a Blueprint for an Object
l Identity, inaccessible state, added behavior
struct Time class BankAccount
{ {
public int hour; ...
public int minute; ...
} }
struct Time class BankAccount
{ {
public int hour; ...
public int minute; ...
} }
Structs
A struct, such as Time in the preceding code, has no identity. If you have two
Time variables both representing the time 12:30, the program will behave
exactly the same regardless of which one you use. Software entities with no
identity are called values. The built-in types described in Module 3, “Using
Value-Type Variables,” in Course 2124A: Introduction to C# Programming for
the Microsoft .NET Platform (Prerelease), such as int, bool, decimal, and all
struct types, are called value types in C#. Value types contain accessible state
and have no added behavior (no methods).
Variables of the struct type are allowed to contain methods, but it is
recommended that they do not. They should contain only data. However, it is
perfectly reasonable to define operators in structs. Operators are stylized
methods that do not add new behavior; they only provide a more concise syntax
for existing behavior.
Module 7: Essentials of Object-Oriented Programming 7
Classes
A class, such as BankAccount in the preceding code, has identity. If you have
two BankAccount objects, the program will behave differently depending on
which one you use. Software entities that have identity are called objects.
(Variables of the struct type are also sometimes loosely called objects, but
strictly speaking they are values.) Types represented by classes are called
reference types in C#. In contrast to structs, nothing but methods should be
visible in a well-designed class. These methods add extra high-level behavior
beyond the primitive behavior present in the lower-level inaccessible data.
Value Types and Reference Types
Value types are the types found at the lowest level of a program. They are the
elements used to build larger softw are entities. Value types can be freely copied
and exist on the stack as local variables or as attributes inside the objects they
describe.
Reference types are the types found at the higher levels of a program. They are
built from smaller software entities. Reference types generally cannot be copied,
and they exist on the heap.

使用道具 举报

回复

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

本版积分规则 发表回复

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