1. 程式人生 > 其它 >C# 基本語法

C# 基本語法

C# 是一種面向物件的程式語言。在面向物件的程式設計方法中,程式由各種相互互動的物件組成。相同種類的物件通常具有相同的型別,或者說,是在相同的 class 中。

例如,以 Rectangle(矩形)物件為例。它具有 length 和 width 屬性。根據設計,它可能需要接受這些屬性值、計算面積和顯示細節。

讓我們來看看一個 Rectangle(矩形)類的實現,並藉此討論 C# 的基本語法:

using System;
namespace RectangleApplication
{
    class Rectangle
    {
        // 成員變數
        double length;
        double width;
        public void Acceptdetails()
        {
            length = 4.5;    
            width = 3.5;
        }
        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: 4.5
Width: 3.5
Area: 15.75

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 包含了三個成員函式: AcceptDetailsGetArea 和 Display

例項化一個類

在上面的程式中,類 ExecuteRectangle 是一個包含 Main() 方法和例項化 Rectangle 類的類。

識別符號

識別符號是用來識別類、變數、函式或任何其它使用者定義的專案。在 C# 中,類的命名必須遵循如下基本規則:

  • 識別符號必須以字母、下劃線或 @ 開頭,後面可以跟一系列的字母、數字( 0 - 9 )、下劃線( _ )、@。
  • 識別符號中的第一個字元不能是數字。
  • 識別符號必須不包含任何嵌入的空格或符號,比如 ? - +! # % ^ & * ( ) [ ] { } . ; : " ' / \。
  • 識別符號不能是 C# 關鍵字。除非它們有一個 @ 字首。 例如,@if 是有效的識別符號,但 if 不是,因為 if 是關鍵字。
  • 識別符號必須區分大小寫。大寫字母和小寫字母被認為是不同的字母。
  • 不能與C#的類庫名稱相同。

C# 關鍵字

關鍵字是 C# 編譯器預定義的保留字。這些關鍵字不能用作識別符號,但是,如果您想使用這些關鍵字作為識別符號,可以在關鍵字前面加上 @ 字元作為字首。

在 C# 中,有些關鍵字在程式碼的上下文中有特殊的意義,如 get 和 set,這些被稱為上下文關鍵字(contextual keywords)。

下表列出了 C# 中的保留關鍵字(Reserved Keywords)和上下文關鍵字(Contextual Keywords):

保留關鍵字
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