建構子,又稱建構函式或建構方法,是一種特殊的函式。
透過建構子,在自類別生成實體物件的同時,能對物件進行「初始化」。
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace ConsoleApp1
- {
- class Car
- {
- public string name; //宣告該類別擁有哪些屬性
- public int wheel;
- public int load;
- public Car() //沒帶任何參數的建構子
- {
- }
- public Car(string name, int wheel, int load) //帶三個參數的建構子
- {
- this.name = name;
- this.wheel = wheel;
- this.load = load;
- }
- public Car(string n, int w) //帶兩個參數的建構子
- {
- name = n;
- wheel = w;
- }
- }
- }
複製代碼- using ConsoleApp1;
- using System;//程式庫呼叫
- using System.ComponentModel.DataAnnotations;
- using System.Linq.Expressions;
- namespace HelloWorld//創建一個程式庫(自己定義)
- {
- class Program//負責一部分工作的人
- {
-
- static void Main()//method ..Entry Point 程式進入點
- {
- Car bus = new Car("公車", 6);
- bus.load = 40;
- Car truck = new Car("卡車", 8, 3);
- Car taxi = new Car("計程車", 4, 5);
-
- Console.WriteLine(bus.name + "有" + bus.wheel + "個輪子,可載" + bus.load + "人.");
- Console.WriteLine(truck.name + "有" + truck.wheel + "個輪子,可載" + truck.load + "人.");
- Console.WriteLine(taxi.name + "有" + taxi.wheel + "個輪子,可載" + taxi.load + "人.");
- }
- }
- }
複製代碼 |