C# 是面向?qū)ο蟮木幊陶Z言。在面向?qū)ο缶幊谭椒ㄖ校绦蛴赏ㄟ^動作相互交互的各種對象組成。 對象可能采取的操作稱為方法。具有相同類型的對象認為是相同的類型,或者說是在同一個類。
例如,假設(shè)有一個Rectangle對象。 它有長度(length)和寬度(width)的屬性。 根據(jù)設(shè)計,它可能需要接受這些屬性的值,計算面積和顯示細節(jié)的方法。
下面我們來看看Rectangle類是如何實現(xiàn)上述功能,并以此學習 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();
}
}
}
當編譯和執(zhí)行上述代碼時,會產(chǎn)生以下結(jié)果:
Length: 10.0
Width: 20.1
Area: 201
任何 C# 程序中的第一個語句一般是:
using System;
using關(guān)鍵字用于在程序中包含命名空間。程序可以包括多個using語句。
class關(guān)鍵字用于聲明一個類。
注釋用于解釋代碼。編譯器忽略注釋中的任何內(nèi)容。 C# 程序中的多行注釋以/*開始,并以*/結(jié)尾,如下所示:
/* This program demonstrates
The basic syntax of C# programming
Language */
單行注釋由“//”符號表示。 例如,
}//end class Rectangle
// 另一個行注釋
變量是用于存儲類的屬性或數(shù)據(jù)成員的數(shù)據(jù)。在前面的程序中,Rectangle類有兩個名為length和width的成員變量。
函數(shù)是執(zhí)行特定任務(wù)的語句集合。類的成員函數(shù)在類中聲明。我們的示例類Rectangle包含三個成員函數(shù):AcceptDetails,GetArea和Display。
在上述程序中,ExecuteRectangle類包含Main()方法,并實例化了一個Rectangle類的實例:r。
標識符是用于標識類,變量,函數(shù)或任何其他用戶定義項目的名稱。 C# 中命名類的基本規(guī)則如下:
0 - 9)或下劃線(_)。 標識符中的第一個字符不能為數(shù)字。?, -, +, !,@,#, %, ^, &, *, (, ), [, ], {, }, ., ;, :, ", ',/ 和\。但是,可以使用下劃線(_)。關(guān)鍵字是預定義為 C# 編譯器的保留字。 這些關(guān)鍵字不能用作標識符。 但是,如果要使用這些關(guān)鍵字作為標識符,但可以使用@字符將關(guān)鍵字前綴來表示某一標識符。
在 C# 中,一些標識符在代碼的上下文中具有特殊意義,例如get和set被稱為上下文關(guān)鍵字。
下表列出了 C# 中的保留關(guān)鍵字和上下文關(guān)鍵字:
保留關(guān)鍵字
| 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 | - | - | - | - | - |
上下文關(guān)鍵字
| add | alias | ascending | descending | dynamic | from | get |
|---|---|---|---|---|---|---|
| global | group | into | join | let | orderby | partial (type) |
| partial(method) | remove | select | set | - | - | - |