C# 是面向對象的編程語言。在面向對象編程方法中,程式由通過動作相互交互的各種對象組成。 對象可能採取的操作稱為方法。具有相同類型的對象認為是相同的類型,或者說是在同一個類。
例如,假設有一個Rectangle
對象。 它有長度(length
)和寬度(width
)的屬性。 根據設計,它可能需要接受這些屬性的值,計算面積和顯示細節的方法。
下麵我們來看看Rectangle
類是如何實現上述功能,並以此學習 C# 的基本語法:
using System;
namespace RectangleApplication
{
class Rectangle
{
// member variables
double length;
double width;
public void Acceptdetails()
{
length = 10.0;
width = 20.1;
}
public double GetArea()
{
return length * width;
}
public void Display()
{
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}
class ExecuteRectangle
{
static void Main(string[] args)
{
Rectangle r = new Rectangle();
r.Acceptdetails();
r.Display();
Console.ReadLine();
}
}
}
當編譯和執行上述代碼時,會產生以下結果:
Length: 10.0
Width: 20.1
Area: 201
using關鍵字
任何 C# 程式中的第一個語句一般是:
using System;
using
關鍵字用於在程式中包含命名空間。程式可以包括多個using
語句。
class關鍵字
class
關鍵字用於聲明一個類。
C# 中的注釋
注釋用於解釋代碼。編譯器忽略注釋中的任何內容。 C# 程式中的多行注釋以/*
開始,並以*/
結尾,如下所示:
/* This program demonstrates
The basic syntax of C# programming
Language */
單行注釋由“//”
符號表示。 例如,
}//end class Rectangle
// 另一個行注釋
成員變數
變數是用於存儲類的屬性或數據成員的數據。在前面的程式中,Rectangle
類有兩個名為length
和width
的成員變數。
成員函數
函數是執行特定任務的語句集合。類的成員函數在類中聲明。我們的示例類Rectangle
包含三個成員函數:AcceptDetails
,GetArea和Display
。
實例化類
在上述程式中,ExecuteRectangle
類包含Main()
方法,並實例化了一個Rectangle
類的實例:r
。
識別字
識別字是用於標識類,變數,函數或任何其他用戶定義專案的名稱。 C# 中命名類的基本規則如下:
- 名稱必須以字母開頭,後面可以有一系列字母,數字(
0 - 9
)或下劃線(_
)。 識別字中的第一個字元不能為數字。 - 它不能包含任何嵌入的空格或符號,如:
?
,-
,+
,!
,@
,#
,%
,^
,&
,*
,(
,)
,[
,]
,{
,}
,.
,;
,:
,"
,'
,/
和\
。但是,可以使用下劃線(_
)。 - 它不能是 C# 關鍵字。
C# 關鍵字
關鍵字是預定義為 C# 編譯器的保留字。 這些關鍵字不能用作識別字。 但是,如果要使用這些關鍵字作為識別字,但可以使用@
字元將關鍵字首碼來表示某一識別字。
在 C# 中,一些識別字在代碼的上下文中具有特殊意義,例如get
和set
被稱為上下文關鍵字。
下表列出了 C# 中的保留關鍵字和上下文關鍵字:
保留關鍵字
abstract | as | base | bool | break | byte | case |
---|---|---|---|---|---|---|
catch | char | checked | class | const | continue | decimal |
default | delegate | do | double | else | enum | event |
explicit | extern | false | finally | fixed | float | for |
foreach | goto | if | implicit | in | in (generic modifier) | int |
interface | internal | is | lock | long | namespace | new |
null | object | operator | out | out (generic modifier) | override | params |
private | protected | public | readonly | ref | return | sbyte |
sealed | short | sizeof | stackalloc | static | string | struct |
switch | this | throw | true | try | typeof | uint |
ulong | unchecked | unsafe | ushort | using | virtual | void |
volatile | while | - | - | - | - | - |
上下文關鍵字
add | alias | ascending | descending | dynamic | from | get |
---|---|---|---|---|---|---|
global | group | into | join | let | orderby | partial (type) |
partial(method) | remove | select | set | - | - | - |