你的位置:首页 > ASP.net教程

[ASP.net教程]第1篇 C#语言基本语句和语法


第1篇 C#语言基本语句和语法

前言:本资料根据【1】整理知识要点,其内容应当是全面的。可供查阅、复习参考。

参考资料:

【1】《BEGINNING VISUAL C#® 2012 PROGRAMMING》

【2】C# 语句大全!

1.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 directivesusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;#endregion

以#开头的内容可视为预指令,他不是C#的关键字。编辑时代码可折叠为1行。

(3)区分大小写。

(4)语句中的空格将不予考虑。

(5)分号“;”为一条语句的结尾。一条语句可书写在2行或多行。

(6)声明语句后面不要分号“;”

(7)注释的方式有三种:

1)/*                         */

特点:以“/*”开始,可书写于多行,只直到有“*/”结束。

2)//

特点:以“//”开头,只能书写于一行。可为单独的一行,也可以放在一条语句的分号之后。

3)///

与//相同。不同的是该方法可由VS提取内容。

(8)占位符标签

程序中的占位符标签类似于汇编语言中的程序指针地址。下图中第2行和第1行为一个标签,因其间无分号相隔。 

<code line 1, statement 1>;<code line 2, statement 2>  <code line 3, statement 2>;

 1.2 声明变量和赋值语句

1.2.1 语法

声明一个变量

<type> <name>;

<type>:变量的类型;<name>:用户定义的变量的名称。

声明多个变量,用逗号隔开

int xSize, ySize;

为一个变量赋值

int myInteger;string myString;myInteger = 17;myString = "\"myInteger\" is";

int xSize, ySize = 5;

xSize使用前尚需初始化

为多个变量赋值

int xSize = 4, ySize = 5;

 1.2.2 变量的类型

 

 

 

 

 1.2.3 变量的命名要点

(1)必须以字母、下划线或@开头,其后可为字母、下划线或数字。
(2)禁用关键字。
(3)区分大小写。
(4)流行的匈牙利命名法,不同类型前以同一前缀。或以作用区分作前缀,但不适合协同编程。
(5)微软建议对于简单的变量使用camelCase命名法,对于高级的使用PascalCase命名法。

 1.2.4 字面值

变量的字面值,许多在字符后面添加一些后缀。有些字面值有很多类型,由VS编译时根据上下文确定。

字符串是引用类型。可使用转义序列、双引号赋值。也可以被赋予null值。

TABLE 3-4: Literal Values
TYPE(S)CATEGORYSUFFIXEXAMPLE/ALLOWED VALUES
bool BooleanNone True or false
int, uint, long, ulong IntegerNone 100
uint, ulongInteger u or U100U
long, ulong Integerl or L100L
ulong Integer ul, uL, Ul, UL, lu, lU,
Lu, or LU
100UL
floatReal f or F1.5F
doubleRealNone, d, or D1.5
decimalRealm or M1.5M
charCharacterNone'a', or escape sequence
string String None"a…a", may include escape sequences

 

 

   
 
 
  
  
  
   
   
   

 

 

 

 

TABLE 3-5: Escape Sequences for String Literals

ESCAPE SEQUENCE

转义序列

CHARACTER PRODUCED

 UNICODE VALUE OF CHARACTER

字符的Unicode值

\' Single quotation mark 单引号0x0027
\"Double quotation mark双引号0x0022
\\ Backslash反斜杠0x005C
\0Null空0x0000
\a Alert (causes a beep)警告(发出一个蜂鸣)0x0007
\bBackspace退格0x0008
\f Form feed换页0x000C
\nNew line换行0x000A
\rCarriage return回车0x000D
\tHorizontal tab 水平制表符0x0009
\vVertical tab垂直制表符0x000B

 

 

 

 
  
 
  
 
  
 
  
  
 
  

 

 

字符串转义举例:

所谓转义,是将有可能破环字符串完整性的符号转换为字符。下列字符串等意:目的是把单引号看作字符串的一个字符

"Karli\'s string.""Karli\u0027s string."

使用@符号,可以不使用“转义序列”:

@"Verbatim string literal."

上例避免某位小数点的影响。下例必须使用@

@"A short list:item 1item 2"

下列字符串等意:

"C:\\Temp\\MyDir\\MyFile.doc"@"C:\Temp\MyDir\MyFile.doc"

1.3 表达式

表达式由运算符和操作数组成。

变量和字面值,称为操作数。

运算符包括数学运算法、逻辑运算符和赋值运算符。运算符按照操作数的数量又分:

➤ Unary — Act on single operands    一元运算符(一个操作数)

➤ Binary — Act on two operands          二元运算符(二个操作数)

➤ Ternary — Act on three operands  三元运算符(三个操作数)

1.3.1 数学运算符

TABLE 3-6: Simple Mathematical Operators
OPERATORCATEGORYEXAMPLE EXPRESSION RESULT
+Binaryvar1 = 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.
%Binaryvar1 = 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类型的操作数(如下表)。而其它运算符不能用于字符串类型的操作数。

TABLE 3-7. The String Concatenation Operator
OPERATORCATEGORYEXAMPLE EXPRESSIONRESULT
+Binaryvar1 = var2 + var3; 

  var1 is assigned the value that is the

concatenation of the two strings stored in var2 and var3.

 

 

 

   

 

TABLE 3-8: Increment and Decrement Operators
OPERATORCATEGORY EXAMPLE EXPRESSIONRESULT
++Unary  var1 = ++var2; var1 is assigned the value of var2 + 1. var2 is incremented by 1.
-- Unaryvar1 = --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。符号在后,结果等于操作数。

1.3.2 赋值运算符

TABLE 3-9: Assignment Operators
OPERATORCATEGORYEXAMPLE EXPRESSION RESULT
=Binary var1 = var2; var1 is assigned the value of var2.
+= Binaryvar1 += var2;var1 is assigned the value that is the sum of var1 and var2.
-= Binaryvar1 -= var2; var1 is assigned the value that is the value of var2 subtracted from the value of var1.
*=Binaryvar1 *= 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.

 

 

 

 

 

 

  
 
 

注意:与+一样,+=也可以用于字符串类型的操作数。

1.3.3   布尔运算符

 

 

 

TABLE 4-4: Boolean Assignment Operators
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 ^.

 

 

 

 

TABLE 4-5: Using the & Bitwise Operator
OPERAND 1 BIT OPERAND 2 BIT & RESULT BIT
1 1 1
1 0 0
0 1 0
0 0 0
TABLE 4-6: Using the | Bitwise Operator
OPERAND 1 BIT OPERAND 2 BIT | RESULT BIT
1 1 1
1 0 1
0 1 1
0 0 0

 

 

TABLE 4-7: Using the ^ Operator
OPERAND 1 BIT OPERAND 2 BIT ^ RESULT BIT
1 1 0
1 0 1
0 1 1
0 0 0
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.
TABLE 4-8: Using the ~ Operator
OPERAND BIT ~ RESULT BIT
1 0
0 1

 

 

 

TABLE 4-10: Bitwise Shift Operators
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.

 

 

 

 

 

 

TABLE 4-11: Bitwise Shift Assignment Operators
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.
Operator Precedence Updated
Now that you have a few more operators to consider, Table 3-10: “Operator Precedence” from the previous
chapter should be updated to include them. The new order is shown in Table 4-12.
TABLE 4-12: Operator Precedence (Updated)
PRECEDENCE OPERATORS
Highest ++, −− (used as prefi xes); (), +, – (unary), !, ˜
*, /, %
+, –
<<, >>
<, >, <=, >=
==, !=
&

|
&&
||
=, *=, /=, %=, +=, −=, <<=, >>=, &=, ^=, |=
Lowest ++, –– (used as suffi xes)

 

 

 

 


  
  

 

 

 

 

 

 

 

1.4 分支和跳转语句

1.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);

1.4.2 分支语句

➤ The ternary operator  三元运算符
➤ The if statement     if语句
➤ The switch statement   switch语句 

1.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" 

1.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.}}}

1.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;}

 1.5 循环语句

➤ do循环

➤ while循环

➤ for循环

➤ 循环的中断语句

无限循环

1.5.1 do循环 

基本语法:

do{  <code to be looped>} while (<Test>);

举例:

int i = 1;do{  Console.WriteLine("{0}", i++);} while (i <= 10);

1.5.2 while循环

语法:

while (<Test>){  <code to be looped>}

举例

int i = 1;while (i <= 10){  Console.WriteLine("{0}", i++);}

1.5.3 for循环

语法:

for (<initialization>; <condition>; <operation>){  <code to loop>}

举例:

int i;for (i = 1; i <= 10; ++i){Console.WriteLine("{0}", i);}

 1.5.4  循环的中断语句 

➤ 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

 1.5.5 无限循环

举例:

while (true){      // code in loop}

 

1.6 高级语句

➤namespace语句    定义名称空间 语句
➤using语句        使用名称空间 语句
➤用户输入语句
➤类型转换语句

 

 

1.6.1 定义名称空间

namespace语句
语法:
namespace LevelOne{  // code in LevelOne namespace  // name "NameOne" defined}// code in global namespace

 

1.6.2 使用名称空间语句

using语句。语法:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace ConsoleApplication1{  ...}

 

 

1.6.3 用户输入语句

语法:

Console.ReadLine()

 

 1.6.4 类型转换语句