網頁

C# 快速導覽 - static 類別及成員

static 關鍵字 (keyword) 可用來修飾類別 (class) 與其成員, static 成員屬於類別,這是說使用 static 成員是透過類別名稱而非物件,此外 static 類別的所有成員都必須是 static



static 類別也無法初始化為物件。


舉例如下
class Demo {
    public static void DoSomething() {
        System.Console.WriteLine("Choice. The problem is choice.");
    }
}

public class DemoTest {
    static void Main() {
        Demo.DoSomething();
    }
}

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


這裡可以看到是直接用 Demo 呼叫 staticDoSomething() 方法
Demo.DoSomething();


編譯執行,結果如下



下例示範 static 類別
static class Demo {
    public static void DoSomething() {
        System.Console.WriteLine("There is no spoon.");
    }
    
    public static void DoSomething2() {
        System.Console.WriteLine("Free your mind.");
    }
}

public class DemoTest {
    static void Main() {
        Demo.DoSomething();
        Demo.DoSomething2();
    }
}

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


編譯執行,結果如下



中英文術語對照
關鍵字keyword
類別class


您可以繼續參考
類別


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


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

沒有留言:

張貼留言

0.留言請選擇註冊帳號, Google 或 OpenID 均可
1.歡迎留言交流,但不歡迎垃圾留言及廣告留言
2.文章相關問題歡迎提出,請減少情緒性留言
3.非文章相關內容,請到 G+ 社群 FB 社團提出
4.問作業之留言會被直接刪除
5.莫忘網路禮節
6.可使用部份HTML標記,如 <b> 、 <i> 、 <a>
7.站長保留刪除留言的權力