首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 進階(二):類別定義、建構子、屬性存取器與靜態方法

     編輯:關於C語言

一、類別概述

類別是建立物件的樣板,定義每個實例包含的資料與功能。

Doctor 類別完整範例

public class Doctor {
    public Doctor() {}
    public Doctor(string name, byte age) {
        this._name = name;
        this._age = age;
    }
    private string _name;
    private byte _age;
    public string Name {
        get { return this._name; }
        set { this._name = value; }
    }
    public byte Age {
        get { return this._age; }
        set { this._age = value; }
    }
    public string DoSth() { return "我會給人治病喔~~"; }
    public static string DoAnth() { return "執行的另一個靜態方法"; }
}

public class OneDoctor {
    static void Main() {
        Doctor dc = new Doctor();
        dc.Name = "李四"; dc.Age = 25;
        Doctor dc2 = new Doctor("張三", 35);
        Console.WriteLine(dc.Name);   // 李四
        Console.WriteLine(dc.Age);    // 25
        Console.WriteLine(dc2.Name);  // 張三
        Console.WriteLine(dc2.Age);   // 35
        Console.WriteLine(dc.DoSth());
        Console.WriteLine(Doctor.DoAnth());
    }
}

重點說明

  • 建構子:同名方法,實例化時自動呼叫。Doctor()、Doctor(string,byte) 為多載建構子。
  • 屬性存取器:get/set 封裝私有欄位,取代 Java 的 getter/setter。
  • 靜態方法:DoAnth() 透過類別名直接呼叫,無需實例化。
  • 類別為參考型別,儲存於受控堆積。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved