C# Chapter 3-8
3 Using GUI Objects and the Visual Studio IDE
先跳过
4 Making Decisions
4.1 Making Decisions Using the if Statement
In some programming languages, such as C++, nonzero numbers evaluate as true and 0 evaluates as false. However, in C#, only Boolean expressions evaluate as true and false.
When you want to execute two or more statements conditionally, you place the statements within a block. A block is a collection of one or more statements contained within a pair of curly braces.
这里和C语言很像,书就看个大概了,注意布尔表达式依然有short-circuit evaluation的特点
and和is keywords
1 | if(num is (>= LOW and <= HIGH)) |
同样地,还有or keyword
C#中,&&, ||被称作conditional AND/OR operator
还有Boolean logical AND/OR operator &和|,它们在放到布尔表达式之间时,会把两边的表达式都evaluate一遍
4.2 Making Decisions Using the switch Statement
C#中,case不会贯穿,顺序也不重要,比如把default放到第一个并不一定会先执行default,每一个case后必须要有break或其他语句结束
同时还可以case后面没有statement
1 | switch(year) |
Using an enumeration with a switch statement.
1 | using System; |
4.3 Using the Conditional Operator
1 | string name = Zuri; |
4.4 Using the NOT Operator
1 | bool oldEnough = (age >= 25); |
Starting with C# version 9, you can use is not to express a negative situation. The following code produces output when the value of num does not fall between two named constants.
1 | if(num is not (>= LOW and <= HIGH)) |
5 Looping
5.1 Creating Loops with the while Statement
A loop is a structure that allows repeated execution of a block of statements. Within a looping structure, a Boolean expression is evaluated. If it is true, a block of statements called the
loop body executes and the Boolean expression is evaluated again.
1 | using static System.Console; |
Often, the value of a loop control variable is not altered by arithmetic but instead is altered by user input. This type of loop is an indefinite loop.
1 | using System; |
5.2 Creating Loops with the for Statement
和C语言基本一样,注意
When a variable (or named constant) can be accessed, it is in scope or in an area where it is known and can be used. When a loop body ends, any declarations made within it are out of scope, which means they are not usable because they have ceased to exist.
1 | for(int k = 0; k < 3; ++k) |
5.3 Creating Loops with the do Statement
1 | do |
5.4 GUI
之前遇到GUI章节应该标记一下的
6 Using Arrays
6.1 Declaring an Array and Assigning Value
An array is a list of data items that
all have the same data type and the same name. Each object in an array is an array element.
数组的名字采用驼峰命名,一般是名词复数,或者在最后加上Table, Array等
After you declare an array variable, you still need to create the actual array because declaring an array and reserving memory space for it are two distinct processes. You can declare an array variable and reserve memory locations for 20 sales objects using the following two statements
1 | double[] sales; |
The keyword new is also known as the new operator; it is used to create objects. In this case, it creates 20 separate sales elements. You also can declare and create an array in one statement, such as the following:
1 | double[] sales = new double[20]; |
If you resize an array in C#, the same identifier refers to a new array in memory, and all the values are set to the default value for the data type.
In C#, arrays are objects. When you instantiate an array, you are creating a specific instance of a class that derives from, or builds upon, the built-in class named System.Array.
当declare数组或者其他对象时,元素会被赋默认值,数字变0,字符变’\u0000’或null,布尔型变false
如果不想要默认初值,可以
1 | int[] myScores = new int[5] {100, 76, 88, 100, 90}; |
这样赋值,每个元素必须都要赋值,不会有只赋值一部分,剩下的为默认值的情况。
字符数组可以赋值给字符串,如
1 | char [] arrayOfLetters = {'h', 'e', 'l', 'l', 'o'}; |
这里new string(...)是构造函数,用来创建和初始化一个string类型的对象
对于字符串,我们也能用下标来得到字符,但字符串并不是一个字符数组
1 | string greeting = "Hello"; |
6.2 Accessing Array Elements
每一个数组都有一个Length property,它的值是元素个数
An array’s Length is a read-only property —— a property you can access, but to which you cannot assign a new value. It is capitalized, as is the convention with all C# property identifiers.
You can easily navigate through arrays using a for or while loop that varies a subscript from 0 through Array.Length - 1. C# also supports a foreach statement that you can use to cycle through every array element without using a subscript. With the foreach statement, you provide a temporary iteration variable that automatically holds each array value in turn.
1 | double[] arr = {1, 2, 3, 4}; |
The foreach iteration variable is read-only—that is, you can access it, but you cannot assign a value to it.
6.3 Using the BinarySearch(), Sort(), and Reverse() Methods
The System.Array class contains a variety of built-in methods that are useful with arrays.
1 | using System; |
BinarySearch()需要两个参数,第一个是数组名,第二个是要找的值,如果找到了,就返回这个值在数组的下标,如果没找到,返回-1,使用前提是数组中的元素是升序的
Sort()将数组升序排序,可以对整数、字符、字符串排序
1 | using static System.Console; |
The Array.Sort() method provides a good example of encapsulation—you can use the method without understanding how it works internally. The method uses an algorithm named Quicksort. (An algorithm is a set of instructions used to solve a problem or perform a task.) (还有和数据结构联动?详见数据结构笔记,不过我可能之后再搬过来或者直接写CS61B的笔记了)
Reverse()逆转整个数组,参数是数组名
6.4 Using Multidimensional Arrays
声明并创建二维数组
1 | double[ , ] sales = new double[3, 4]; |
也可以三维数组,例如,有三栋楼,每栋楼有两层,每一层有两种房间,两种房间价格不同
1 | int[ , , ] rents = { |
A jagged array is a one-dimensional array in which each element is another array. The major difference between jagged and rectangular arrays is that in jagged arrays, each row can be a different length.
假如我们要统计五条路线的每个车站的票价,有的路线有2个站,有的有10个
1 | double[][] tickets = { |
有点像C语言中的指针数组?没记错的话在C语言中二维数组是个二重指针?有些忘了,记得这是当时学C语言最难理解的地方
6.6 GUI
7 Using Methods
7.1 Understanding Methods and Implementation Hiding
A method is an encapsulated series of statements that carry out a task. Any class can contain an unlimited number of methods.
The WriteLine() method provides an example of implementation hiding, which means keeping the details of a method’s operations hidden. A method that uses another is a method client.
7.2 Writing Methods with No Parameters and No Return Value
The method header defines the rules for using the method. It contains:
- Optional declared accessibility
- An optional static modifier
- The return type for the method
- The method name, or identifier
- An opening parenthesis
- An optional list of method parameters (separated with commas if there is more than one parameter)
- A closing parenthesis
The optional declared accessibility for a method sets limits as to how other methods can use the method.

- Public access is established by including a
publicmodifier in the member declaration. This modifier allows access to the method from other classes. - Private access is established by including a private modifier in the member declaration or by omitting any accessibility modifier. This modifier limits method access to the class that
contains the method.
You can declare a method to be static or nonstatic. If you use the keyword modifier static, you indicate that a method can be called without referring to an object. Instead, you refer only to the class.
如果我们有一个叫A的类,里面有一个静态method叫methodA(),可以这样调用
- 如果从另一个类的某method里调用
methodA(),说明methodA()是public的 - 如果是在同一个类的另一个method里调用
methodA(),可以直接调用
1 | // 1. |
method默认是nonstatic的
Every method has a return type, indicating what kind of value the method will return to any other method that calls it. If a method does not return a value, its return type is void. A method’s return type is known more succinctly as a method’s type.
A parameter to a method is a variable between parentheses in a method header that holds data passed to the method when the method is called. The terms argument and parameter are closely related. An argument is data in a method call, and a parameter is in the method header—it receives an argument’s value when the method executes.
The first methods you write in console applications will be private, static, and void and will have empty parameter lists.
That means they won’t be called from other classes, they won’t require an object reference, they will not return any value to their calling method, and they will not accept any data from the outside.
在一个类中,method的顺序不重要
1 | using static System.Console; |
The ShowWelcome() method in the HelloClass class is static, and therefore it is called from the Main() method without an object reference (that is, without an object name and a dot
before the method name). It also resides in the same class as the Main() method, so it can be called without using its class name.
Each of two different classes can have its own method named ShowWelcome(). Such a method in the second class would be entirely distinct from the identically named method in the first class.
The complete name of this method is HelloClass.ShowWelcome(), but you do not need to use the complete name when calling the method within the same class.
If another class named SomeOtherClass had a public static method with the same name, you could call the method from HelloClass using the following statement.
1 | SomeOtherClass.ShowWelcome(); |
You have learned that the area of a program in which a variable or named constant is known is called its scope. Variables and constants that are declared within a method are in scope only from the point at which they are declared to the end of the method. Programmers also say that the variable is a local variable.
7.3 Writing Methods that Require Arguments
注意formal parameter和actual parameter区别,formal parameter receives a copy of the value passed to it.
其他和C语言一样
7.4 Writing Methods that Return a Value
一个method最多只能返回一个值给调用它的method
The system keeps track of where to return after a method call in an area of memory called the stack.
Another area of memory called the heap is where memory can be allocated while a program is executing.
7.5 Passing Array Values to a Method
You indicate that a method parameter must be an array by placing square brackets after the data type in the method’s parameter list. When you pass an array to a method, changes you make to array elements within the method are reflected in the original array that was sent to the method.
A memory address is also known as a reference. Arrays, like all objects but unlike built-in types such as double and int, are passed by reference.
When a simple built-in type is passed to a method, it is passed by value. In other words, the method receives a copy of the value at a new memory address.
However, when an array is passed to a method, the method receives the actual memory address of the array and has access to the actual values in the array elements.
1 | using static System.Console; |
如果要多维数组或者交错数组(jagged array)做参数,可以
1 | private static void displayScores(int[ , ] scoresArray) |
7.6 Alternate Ways to Write a Main() Method Header
7.6.1 With a Parameter List
1 | static void Main(string[] args) |
Use this format for the Main() method header if you need to access command-line arguments passed in to your application.
1 | using static System.Console; |
7.6.2 With an Integer Return Type
最后要return 0
7.6.3 With public Access
In particular, Java programmers might prefer using public because the style is conventional for them. If a class’s Main() method is public, it can be called from another class by using its fully qualified name.
7.7 GUI
8 Advanced Method Concepts
8.1 An Overview of C#’s Parameter Types
Methods can receive parameters that are:
- Passed by value or passed by reference
- Mandatory(法定的,义务的) or optional
- When a value is passed by value, the method receives a copy of the value and cannot alter the original.
- When a value is passed by reference, the method receives the memory address and can alter the original.
- A mandatory parameter to a method is one that is required in every method call.
- An optional parameter to a method is one for which a default value is automatically supplied if you do not explicitly send one as an argument.
Mandatory parameters include:
- Value parameters, when they are declared without default values
- Reference parameters
- Output parameters
- Parameter arrays
8.1.1 Using Mandatory Value Parameters
When you use a value parameter in a method header, you indicate the parameter’s type and name, and the method receives a copy of the value passed to it.
The actual parameter (the argument in the calling method) and the formal parameter (the parameter in the method header) refer to two separate memory locations, and the called method receives a copy of the sent value. Changes to value parameters within a method never affect the values of the original arguments named in calling statements.
8.2 Passing Parameters by Reference
When you use a reference parameter, output parameter, or parameter array, you pass a memory address to a method, allowing the called method to alter the original variable’s value.
8.2.1 Using a ref Parameter
ref is a modifier to indicate a reference parameter.
下面的例子中,number和x是共享地址的
1 | using static System.Console; |
8.2.2 Using an out Parameter
When you use a reference parameter, any passed variable must have an assigned value. Using an output parameter is convenient when the passed variable doesn’t have a value yet.
1 | using System; |
还可以在变量作为out参数传递时声明这个变量,这个变量叫out variable
1 | InputMethod(out int first, out int second); |
1 | using static System.Console; |
TryParse()函数接受要转换的字符串参数和一个存储转换结果的参数,如果转换失败,返回false并把第二个参数赋值为0,转换成功就返回true并把第二个参数赋值为转换结果
8.2.3 Using Parameter Arrays
When you don’t know how many arguments of the same data type might eventually be sent to a method, you can declare a parameter array—a local array declared within the method header using the keyword
params. Such a method accepts any number of elements that are all the same data type.
When a method header uses the params keyword, two restrictions apply:
- Only one params keyword is permitted in a method declaration.
- If a method declares multiple parameters, the params-qualified parameter must be the last one in the list.
1 | using static System.Console; |
8.3 Returning a Reference from a Method
1 | using System; |
这个程序中,形参elements是传递数组的,数组传递进函数实际上是把数组的地址传进来了,所以返回的ref elements[position]是真实的地址,就是items[position]的地址
You can return a reference from a method if the reference was passed into the method, but you cannot return a reference if the value was passed into the method.
8.4 Overloading Methods
Overloading involves the ability to write multiple versions of a method using the same method name.
When you overload a C# method, you write multiple method implementations with the same name but different parameter lists. A method’s name and parameter list constitute the method’s signature.
1 | using static System.Console; |

