第1篇 C#语言基本语句和语法
第1篇 C#语言基本语句和语法
前言:本资料根据【1】整理知识要点,其内容应当是全面的。可供查阅、复习参考。
参考资料:
【1】《BEGINNING VISUAL C#® 2012 PROGRAMMING》
【2】C# 语句大全!
1、 C#程序基本结构和语法要点
Here, you’ll take a closer look at the console application example and break down the structure a bit. Here’s the code:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;
namespace ConsoleApplication1 { class Program { static void Main(string[] args) { // Output text to the screen. Console.WriteLine("The first app in Beginning C# Programming!"); Console.ReadKey(); } } }
(1)所有的C#程序后缀为.cs
(2)编辑时,为使用代码大纲(代码折叠)功能,可如下:
#region Using directives using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; #endregion
以#开头的内容可视为预指令,他不是C#的关键字。编辑时代码可折叠为1行。
(3)区分大小写。
(4)语句中的空格将不予考虑。
(5)分号“;”为一条语句的结尾。一条语句可书写在2行或多行。
(6)声明语句后面不要分号“;”
(7)注释的方式有三种:
➤ /* */
/* */
特点:以“/*”开始,可书写于多行,只直到有“*/”结束。
➤ //
//
特点:以“//”开头,只能书写于一行。可为单独的一行,也可以放在一条语句的分号之后。
➤ ///
///
与//相同。不同的是该方法可由VS提取内容。
(8)占位符标签
程序中的占位符标签类似于汇编语言中的程序指针地址。下图中第2行和第1行为一个标签,因其间无分号相隔。
<code line 1, statement 1>; <code line 2, statement 2> <code line 3, statement 2>;
➤ 关于类、接口、Sub子程序和变量修饰符
类,以某种参数实例化后即成为对象。我这样理解:对象就是程序中的实体,一个UI或一个数据结构,类是一些实体的共有属性的集合。类可以通过XAML标记语言编程设计而定义,这种类一般用作UI或UI元素;类也可以通过C#代码编程设计而定义,通过C#代码,既可以定义用作UI或UI元素的类,可以定义数据结构的类。UI或UI元素的类不是本篇讨论的内容。
C#编程与汇编语言编程完全不同。后者是为CPU编写代码,程序是顺序结构,设计人员要用的是CPU。C#语言编程不是顺序结构,基本与CPU无关,用的是微软的操作系统,运行时,不是C#代码在运行,而是操作系统在运行,C#代码为操作系统提供一些任务,由微软操作系统完成。这些代码必须符合微软操作系统的规定,微软把这些规定商业包装成.Net,为便于编程者使用.net,微软设计了WPF、XAML、C#三个东西,你就是用这三样东西来设计你的应用程序。XAML用于设计UI,C#代码负责UI所体现的信息的处理。UI上产生“事件”,C#代码处理事件,微软称此对事件处理的程序为“方法”,方法就是一个个的sub子程序。
定义变量的场合因此有三处,类的内外,sub的内外。类型则有临时有效或永久有效。C#通过变量修饰符为变量设定类型。
2、 名称空间、类和接口
2.1 定义和使用名称空间
➤ namespace语句。定义名称空间。语法:
namespace LevelOne
{
// code in LevelOne namespace
// name "NameOne" defined
}
// code in global namespace
➤ using语句。使用名称空间。语法:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
...
}
2.2 定义类、声明类的属性
➤ internal。该修饰符声明类是内部的,仅本项目使用。可省略。
internal class MyClass { // Class members. }
➤ public。声明类是公共的,可由其他项目中的代码来访问。
public class MyClass { // Class members. }
➤ abstract。抽象类。不能实例化,只能继承。下例中public亦可为internal。
public abstract class MyClass { // Class members, may be abstract. }
➤ sealed。密封类。不能继承。下例中public亦可为internal。
下例为定义一个密封类。
public sealed class MyClass { // Class members. }
下例为使用一个密封类。
public class MyClass : MyBase { // Class members. }
注意,在C#的类定义中,只能有一个基类。如果继承了一个抽象类,该派生类除非也是抽象的,就必须实现继承该抽象类的所有抽象成员。编译器不允许派生类访问高于该基类的类。也就是说,内部类可继承于一个公共基类,但公共基类不能继承于一个内部类。
在类的继承层次结构中,所有的类的根都是System.Object。如果没有使用基类,则所定义的类就只继承于基类System.Object。
➤ 为类指定接口。语法:
[public] class MyClass :[ MyBase, ]IMyInterface[, IMySecondInterface][, ...] { // Class members. }
2.3 定义接口、声明接口的属性
➤ public interface 下例:定义一个接口。
接口修饰符为public或internal;无abstract和sealed。接口无根。
[public ]interface IMyInterface { // Interface members. }
➤ 接口继承。下例:定义一个接口,该接口可以继承于多个接口。
public interface IMyInterface : IMyBaseInterface, IMyBaseInterface2 { // Interface members. }
3、 变量和表达式
3.1 变量
3.1.1 变量命名要点
(1)必须以字母、下划线或@开头,其后可为字母、下划线或数字。
(2)禁用关键字。
(3)区分大小写。
(4)流行的匈牙利命名法,不同类型前以同一前缀。或以作用区分作前缀,但不适合协同编程。
(5)微软建议对于简单的变量使用camelCase命名法,对于高级的使用PascalCase命名法。
3.1.2 声明变量
➤ 声明一个变量
<type> <name>;
<type>:变量的类型(见<type>可选的内容和含义);<name>:用户定义的变量的名称。
➤ 声明多个变量,用逗号隔开
int xSize, ySize;
3.1.3 为变量赋值
➤ 为一个变量赋值
int myInteger;
string myString;
myInteger = 17;
myString = "\"myInteger\" is";
int xSize, ySize = 5;
xSize使用前尚需初始化
➤ 为多个变量赋值
int xSize = 4, ySize = 5;
3.1.4 变量的作用域关键字
➤ 全局变量和局部变量
3.2 字面值
表达式由运算符和操作数组成。变量和字面值,称为操作数。运算符包括数学运算法、逻辑运算符和赋值运算符。运算符按照操作数的数量又分:
➤ Unary — Act on single operands 一元运算符(一个操作数)
➤ Binary — Act on two operands 二元运算符(二个操作数)
➤ Ternary — Act on three operands 三元运算符(三个操作数)
3.2.1 变量的字面值
➤ 字面值后缀
许多变量的字面值,在字符后面添加一些后缀,表示类型。有些字面值有很多类型,由VS编译时根据上下文确定。
TYPE(S) | CATEGORY | SUFFIX | EXAMPLE/ALLOWED VALUES |
bool | Boolean | None | True or false |
int, uint, long, ulong | Integer | None | 100 |
uint, ulong | Integer | u or U | 100U |
long, ulong | Integer | l or L | 100L |
ulong | Integer | ul, uL, Ul, UL, lu, lU, Lu, or LU |
100UL |
float | Real | f or F | 1.5F |
double | Real | None, d, or D | 1.5 |
decimal | Real | m or M | 1.5M |
char | Character | None | 'a', or escape sequence |
string | String | None | "a…a", may include escape sequences |
➤ 字符串转义
所谓转义,是将有可能破环字符串完整性的符号转换为字符。
字符串是引用类型。可使用转义序列、双引号赋值。也可以被赋予null值。
ESCAPE SEQUENCE 转义序列 |
CHARACTER PRODUCED |
UNICODE VALUE OF CHARACTER 字符的Unicode值 |
\' | Single quotation mark 单引号 | 0x0027 |
\" | Double quotation mark双引号 | 0x0022 |
\\ | Backslash反斜杠 | 0x005C |
\0 | Null空 | 0x0000 |
\a | Alert (causes a beep)警告(发出一个蜂鸣) | 0x0007 |
\b | Backspace退格 | 0x0008 |
\f | Form feed换页 | 0x000C |
\n | New line换行 | 0x000A |
\r | Carriage return回车 | 0x000D |
\t | Horizontal tab 水平制表符 | 0x0009 |
\v | Vertical tab垂直制表符 | 0x000B |
字符串转义举例:
下列字符串等意:目的是把单引号看作字符串的一个字符
"Karli\'s string." "Karli\u0027s string."
使用@符号,可以不使用“转义序列”:
@"Verbatim string literal."
上例避免某位小数点的影响。下例必须使用@
@"A short list: item 1 item 2"
下列字符串等意:
"C:\\Temp\\MyDir\\MyFile.doc" @"C:\Temp\MyDir\MyFile.doc"
3.3 运算符
➤ 简单数学运算符
OPERATOR | CATEGORY | EXAMPLE EXPRESSION | RESULT |
+ | Binary | var1 = var2 + var3; | var1 is assigned the value that is the sum of var2 and var3. |
- | Binary | var1 = var2 - var3; |
var1 is assigned the value that is the value of var3 subtracted from the value of var2. |
* | Binary | var1 = var2 * var3; | var1 is assigned the value that is the product of var2 and var3. |
/ | Binary | var1 = var2 / var3; | var1 is assigned the value that is the result of dividing var2 by var3. |
% | Binary | var1 = var2 % var3; |
var1 is assigned the value that is the remainder when var2 is divided by var3. |
+ | Unary | var1 = +var2; | var1 is assigned the value of var2. |
- | Unary | var1 = -var2; | var1 is assigned the value of var2 multiplied by -1. |
➤ char类型和string类型运算符
注意,char类型变量的操作数不能使用上表的简单数学运算符,否则得到的结果是一个数值。
上述+可用于string类型的操作数(如下表)。而其它运算符不能用于字符串类型的操作数。
OPERATOR | CATEGORY | EXAMPLE EXPRESSION | RESULT |
+ | Binary | var1 = var2 + var3; |
var1 is assigned the value that is the concatenation of the two strings stored in var2 and var3. |
➤ 加/减运算符
OPERATOR | CATEGORY | EXAMPLE EXPRESSION | RESULT |
++ | Unary | var1 = ++var2; | var1 is assigned the value of var2 + 1. var2 is incremented by 1. |
-- | Unary | var1 = --var2; | var1 is assigned the value of var2 - 1. var2 is decremented by 1. |
++ | Unary | var1 = var2++; | var1 is assigned the value of var2. var2 is incremented by 1. |
-- | Unary | var1 = var2--; | var1 is assigned the value of var2. var2 is decremented by 1. |
操作数var2总是加1或减1。符号在前,结果等于操作数加1或减1。符号在后,结果等于操作数。
➤ 赋值运算符
OPERATOR | CATEGORY | EXAMPLE EXPRESSION | RESULT |
= | Binary | var1 = var2; | var1 is assigned the value of var2. |
+= | Binary | var1 += var2; | var1 is assigned the value that is the sum of var1 and var2. |
-= | Binary | var1 -= var2; | var1 is assigned the value that is the value of var2 subtracted from the value of var1. |
*= | Binary | var1 *= var2; | var1 is assigned the value that is the product of var1 and var2. |
/= | Binary | var1 /= var2; | var1 is assigned the value that is the result of dividing var1 by var2. |
%= | Binary | var1 %= var2; | var1 is assigned the value that is the remainder when var1 is divided by var2. |
注意:与+一样,+=也可以用于字符串类型的操作数。
➤ 布尔比较运算符
OPERATOR | CATEGORY | EXPRESSION | RESULT |
== | Binary | var1 = var2 == var3; |
var1 is assigned the value true if var2 is equal to var3, or false otherwise. |
!= | Binary | var1 = var2 != var3; |
var1 is assigned the value true if var2 is not equal to var3, or false otherwise. |
< | Binary | var1 = var2 < var3; |
var1 is assigned the value true if var2 is less than var3, or false otherwise. |
> | Binary | var1 = var2 > var3; |
var1 is assigned the value true if var2 is greater than var3, or false otherwise. |
<= | Binary | var1 = var2 <= var3; |
var1 is assigned the value true if var2 is less than or equal to var3, or false otherwise. |
>= | Binary | var1 = var2 >= var3; |
var1 is assigned the value true if var2 is greater than or equal to var3,or false otherwise. |
➤ 布尔值运算符
OPERATOR | CATEGORY | EXAMPLE EXPRESSION | RESULT |
! | Unary | var1 = !var2; |
var1 is assigned the value true if var2 is false, or false if var2 is true. (Logical NOT) |
& | Binary | var1 = var2 & var3; |
var1 is assigned the value true if var2 and var3 are both true, or false otherwise.(Logical AND) |
| | Binary | var1 = var2 | var3; |
var1 is assigned the value true if either var2 or var3 (or both) is true,or false otherwise.(Logical OR) |
∧ | Binary | var1 = var2 ∧ var3; |
var1 is assigned the value true if either var2 or var3, but not both, is true, or false otherwise. (Logical XOR or exclusive OR) |
➤ 条件布尔运算符
OPERATOR | CATEGORY | EXAMPLE EXPRESSION | RESULT |
&& | Binary | var1 = var2 && var3; |
var1 is assigned the value true if var2 and var3 are both true, or false otherwise.(Logical AND) |
|| | Binary | var1 = var2 || var3; |
var1 is assigned the value true if either var2 or var3 (or both) is true, or false otherwise. (Logical OR) |
➤ 布尔赋值运算符
OPERATOR | CATEGORY | EXAMPLE EXPRESSION | RESULT |
&= | Binary | var1 &= var2; | var1 is assigned the value that is the result of var1 & var2. |
|= | Binary | var1 |= var2; | var1 is assigned the value that is the result of var1 | var2. |
^= | Binary | var1 ^= var2; | var1 is assigned the value that is the result of var1 ^ var2. |
These work with both Boolean and numeric values in the same way as &, |, and ^.
➤ 按位运算符
OPERAND 1 BIT | OPERAND 2 BIT | & RESULT BIT |
1 | 1 | 1 |
1 | 0 | 0 |
0 | 1 | 0 |
0 | 0 | 0 |
OPERAND 1 BIT | OPERAND 2 BIT | & RESULT BIT |
1 | 1 | 1 |
1 | 0 | 1 |
0 | 1 | 1 |
0 | 0 | 0 |
OPERAND 1 BIT | OPERAND 2 BIT | & RESULT BIT |
1 | 1 | 0 |
1 | 0 | 1 |
0 | 1 | 1 |
0 | 0 | 0 |
OPERAND BIT | ~ RESULT BIT |
1 | 0 |
0 | 1 |
C# also allows the use of a unary bitwise operator (~), which acts on its operand by inverting each of its bits,so that the result is a variable having values of 1 for each bit in the operand that is 0, and vice versa. This is shown in Table 4-8.
➤ 移位运算符
OPERATOR | CATEGORY | EXAMPLE EXPRESSION | RESULT |
>> | Binary | var1 = var2 >> var3; |
var1 is assigned the value obtained when the binary content of var2 is shifted var3 bits to the right. |
<< | Binary | var1 = var2 << var3; |
var1 is assigned the value obtained when the binary content of var2 is shifted var3 bits to the left. |
➤ 移位赋值运算符
OPERATOR | CATEGORY | EXAMPLE EXPRESSION | RESULT |
>>= | Unary | var1 >>= var2; |
var1 is assigned the value obtained when the binary content of var1 is shifted var2 bits to the right. |
<<= | Unary | var1 <<= var2; |
var1 is assigned the value obtained when the binary content of var1 is shifted var2 bits to the left. |
3.4 运算符优先级
PRECEDENCE | OPERATORS |
Highest |
++, −− (used as prefi xes); (), +, – (unary), !, ˜ |
Lowest | ++, –– (used as suffi xes) |
3.5 数据类型转换(显式转换)
语法:
(<destinationType>)<sourceVar>
举例:
byte destinationVar; short sourceVar = 7; destinationVar = (byte)sourceVar; Console.WriteLine("sourceVar val: {0}", sourceVar); Console.WriteLine("destinationVar val: {0}", destinationVar);
➤ 使用Convert 命令
COMMAND | RESULT |
Convert.ToBoolean(val) | val converted to bool |
Convert.ToByte(val) | val converted to byte |
Convert.ToChar(val) | val converted to char |
Convert.ToDecimal(val) | val converted to decimal |
Convert.ToDouble(val) | val converted to double |
Convert.ToInt16(val) | val converted to short |
Convert.ToInt32(val) | val converted to int |
Convert.ToInt64(val) | val converted to long |
Convert.ToSByte(val) | val converted to sbyte |
Convert.ToSingle(val) | val converted to float |
Convert.ToString(val) | val converted to string |
Convert.ToUInt16(val) | val converted to ushort |
Convert.ToUInt32(val) | val converted to uint |
Convert.ToUInt64(val) | val converted to ulong |
Here, val can be most types of variable (if it’s a type that can’t be handled by these commands, the compiler will tell you).
4 、分支和跳转语句
4.1 跳转语句
➤goto 语句
The goto statement is used as follows:
goto <labelName>;
Labels are defi ned as follows:
<labelName>:
For example, consider the following:
int myInteger = 5; goto myLabel; myInteger += 10; myLabel: Console.WriteLine("myInteger = {0}", myInteger);
4.2 分支语句
➤ The ternary operator 三元运算符
➤ The if statement if语句
➤ The switch statement switch语句
4.2.1 三元运算符
常用于简单赋值,较复杂的代码宜用if语句。
The syntax is asfollows:
<test> ? <resultIfTrue>: <resultIfFalse>
Here,<test> is evaluated to obtain a Boolean value, and the result of the operator is either <resultIfTrue> or <resultIfFalse> based on this value.
You might use this as follows to test the value of an int variable called myInteger:
string resultString = (myInteger < 10) ? "Less than 10" : "Greater than or equal to 10";
如果myInteger<10,则:resultString = "Less than 10"
如果myInteger≥10,则:resultString = "Greater than or equal to 10"
4.2.2 if语句
The syntax is asfollows:
if (<test>) <code executed if <test> is true>;
if (<test>) <code executed if <test> is true>; else <code executed if <test> is false>;
if (<test>) { <code executed if <test> is true>; } else { <code executed if <test> is false>; }
举例:
static void Main(string[] args) { string comparison; Console.WriteLine("Enter a number:"); double var1 = Convert.ToDouble(Console.ReadLine()); Console.WriteLine("Enter another number:"); double var2 = Convert.ToDouble(Console.ReadLine()); if (var1 < var2) comparison = "less than"; else { if (var1 == var2) comparison = "equal to"; else comparison = "greater than"; } Console.WriteLine("The first number is {0} the second number.",comparison); Console.ReadKey(); }
举例:判断更多的条件:
if (var1 == 1) { // Do something. } else { if (var1 == 2) { // Do something else. } else { if (var1 == 3 || var1 == 4) { // Do something else. } else { // Do something else. } } }
4.2.3 switch语句
标准语法:The basic structure of a switch statement is as follows:
switch (<testVar>) { case <comparisonVal1>: <code to execute if <testVar> == <comparisonVal1> > break; case <comparisonVal2>: <code to execute if <testVar> == <comparisonVal2> > break; ... case <comparisonValN>: <code to execute if <testVar> == <comparisonValN> > break; default: <code to execute if <testVar> != comparisonVals> break; }
使用技巧:
{ case <comparisonVal1>: <code to execute if <testVar> == <comparisonVal1> > goto case <comparisonVal2>; case <comparisonVal2>: <code to execute if <testVar> == <comparisonVal2> > break; ...
switch (<testVar>) { case <comparisonVal1>: case <comparisonVal2>: <code to execute if <testVar> == <comparisonVal1> or <testVar> == <comparisonVal2> > break; ...
switch (myInteger) { case 1: <code to execute if myInteger == 1> break; case −1: <code to execute if myInteger == −1> break; default: <code to execute if myInteger != comparisons> break; }
5、循环语句
➤ do循环
语法:
do { <code to be looped> } while (<Test>);
举例:
int i = 1; do { Console.WriteLine("{0}", i++); } while (i <= 10);
➤ while循环
语法:
while (<Test>) { <code to be looped> }
举例
int i = 1; while (i <= 10) { Console.WriteLine("{0}", i++); }
➤ for循环
语法:
for (<initialization>; <condition>; <operation>) { <code to loop> }
举例:
int i; for (i = 1; i <= 10; ++i) { Console.WriteLine("{0}", i); }
➤ 循环的中断语句
➤ break — Causes the loop to end immediately
➤ continue — Causes the current loop cycle to end immediately (execution continues with the next loop cycle)
➤ goto — Allows jumping out of a loop to a labeled position (not recommended if you want your code to be easy to read and understand)
➤ return — Jumps out of the loop and its containing function (see
➤ 无限循环
举例:
while (true) { // code in loop }
6、高级语句
➤ 用户输入语句
语法:
Console.ReadLine()
➤ 类型转换语句