第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編譯時根據上下文確定。

TABLE 3-4: Literal Values
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值。

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
\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 運算符

 ➤  簡單數學運算符 

TABLE 3-6: Simple Mathematical Operators
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類型的操作數(如下表)。而其它運算符不能用於字符串類型的操作數。 

TABLE 3-7. The String Concatenation Operator
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.

 

 

   

 

 

 

➤  加/減運算符

TABLE 3-8: Increment and Decrement Operators
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。符號在后,結果等於操作數。

➤  賦值運算符

TABLE 3-9: Assignment Operators
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.

 

 

 

 

 注意:與+一樣,+=也可以用於字符串類型的操作數。

➤  布爾比較運算符

TABLE 4-1: Boolean Comparison Operators
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.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

➤  布爾值運算符

TABLE 4-2: Boolean Operators for Boolean Values
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)

 

 

 

 

 

 

 


   
  
  

➤  條件布爾運算符

TABLE 4-3: Conditional Boolean Operators
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)

 

 

 

 

 

 

➤  布爾賦值運算符

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 ^ Bitwise Operator
OPERAND 1 BIT OPERAND 2 BIT  & RESULT BIT
1 1 0
1 0 1
0 1 1
0 0 0

 

 

 

 

 

 

TABLE 4-8: Using the ~ Bitwise Operator
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.

➤  移位運算符

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.


   
   
 

 

 

 

3.4 運算符優先級

TABLE 4-12: Operator Precedence (Updated)
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 命令

TABLE 5-2: Convert Commands
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;
  case1:
    <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()

 ➤  類型轉換語句

 

 

 

 

 
        

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM