C# 快速導覽 - 類別

類別 (class) 是物件 (object) 的模板,物件的所有功能都由類別設置。



基本上 C# 程式至少由一個類別構成,可執行的類別就得設定 Main() 方法 (method) ,方法是類別的成員之一,這是專屬於物件的功能模組,可以設置指定的工作,另外屬性 (proterty) 為物件所帶有的變數 (variable) ,也是成員之一。


宣告類別使用關鍵字 (keyword) class ,例如
// 宣告類別
class Demo {
    // 宣告成員及定義
    
    // Main() 方法
    static void Main() {
        // 程式的執行內容
    }
}


舉例如下
class Demo {
    int a;
    int b;
    
    int DoSomething() {
        return a + b;
    }
    
    static void Main() {
        Demo d = new Demo();
        d.a = 11;
        d.b = 22;
        System.Console.WriteLine(d.DoSomething());
    }     
}

/* 《程式語言教學誌》的範例程式
    http://pydoing.blogspot.com/
    檔名:class01.cs
    功能:示範 C# 程式 
    作者:張凱慶
    時間:西元 2013 年 6 月 */


此例在類別 Demo 宣告兩個 int 屬性 ab
int a;
int b;


除了 Main() 方法之外,另外定義一個 DoSomething() 方法,內容很簡單,就是回傳屬性 ab 的相加值。
int DoSomething() {
    return a + b;
}


方法可以有參數 (parameter) 及回傳值 (return value) ,參數為提供給方法計算的值,回傳值則是方法回傳給呼叫方法的數值,有回傳值的方法把回傳值放在 return 陳述裡,也可以放運算式 (expression) 。沒有參數的方法在方法名稱後的小括弧留空,沒有回傳值的方法則宣告為 void


Main() 為程式執行的方法,此例在 Main() 中建立 Demo 型態的物件變數 d ,然後用小數點運算子設定屬性 ab 的值,最後呼叫 DoSomething() 印出回傳值
static void Main() {
    Demo d = new Demo();
    d.a = 11;
    d.b = 22;
    System.Console.WriteLine(d.DoSomething());
}


為什麼可以 Demo 中建立同屬於 Demo 的物件呢?這是因為 Main() 為 static 的關係, static 屬於類別而非物件, static 成員使用屬於物件的屬性與方法都得用建立物件的方式唷!


編譯執行,結果如下



下例示範定義有參數的方法
class Demo {
    int DoSomething(int a, int b) {
        int c = a + b;
        System.Console.WriteLine(c);
        return c;
    }   
    
    void DoSomething2() {
        System.Console.WriteLine("There is no spoon.");
    }
    
    static void Main() {
        Demo d = new Demo();
        d.DoSomething(44, 55);
        d.DoSomething2();
    }
}

/* 《程式語言教學誌》的範例程式
    http://pydoing.blogspot.com/
    檔名:class02.cs
    功能:示範 C# 程式 
    作者:張凱慶
    時間:西元 2013 年 6 月 */


參數可以有多個,要把型態與參數名稱寫在小括弧中,然後以逗點區隔,但是回傳值只能有一個
int DoSomething(int a, int b) {


編譯執行,結果如下



中英文術語對照
類別class
物件object
方法method
屬性proterty
變數variable
關鍵字keyword
參數parameter
回傳值return value
運算式expression


您可以繼續參考
類別


相關目錄
回 C# 快速導覽
回 C# 教材
回首頁


參考資料
Standard ECMA-334 C# Language Specification
msdn: 類別 (C# 程式設計手冊)

沒有留言: