C# - 建構子

問題:

  1. 建構物件要寫多行程式碼
  2. 重複設定同樣的數值
1
2
3
4
5
6
7
8
9
10
private void button1_Click(object sender, EventArgs e)
{
Student s1 = new Student();
s1.Name = "小山";
s1.Grade = 3;

Student s2 = s1;
s2.Name = "小羊";
s2.Grade = 2;
}

Constructor

  • Method 的一種
  • 物件被建立的時候執行
  • 沒有 output
  • 名稱與 class 名稱相同
  • 如果知道某個屬性的初始值為多少,可寫在建構子內,讓物件預先設定好
1
2
3
4
5
6
7
8
9
10
11
class Student
{

public int Grade;

public Student()//建構子
{
Grade = 1;
}

}
  • 建構子可以給予 input(引數、輸入值)用來幫助設定物件
1
2
3
4
5
6
7
8
9
10
11
12
class Student
{

public int Grade;
public int StudentID;
public string Name;
public Student()//建構子
{
Grade = 1;
}

}
  • 建構子的 input 要在建立物件時給予
1
Student s1 = new Student(10201,"zzz");
  • Overloaded 多載
    不同情況需要不同建構子。可以使用物件導向的其中一個特徵「多載」。

可寫兩個名稱一樣的建構子,但是接受不同數量的 input

1
2
3
4
5
6
7
private void button1_Click(object sender, EventArgs e)
{
Student s1 = new Student(10201,"aa");
Student s2 = new Student(10202, "bb");
Student s3 = new Student(10202, "正正",3);

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Student
{
public int StudentID;
public string Name;
public int Grade;
public Student(int studentID, string name, int grade)
{
StudentID = studentID;
Name = name;
Grade = grade;
}
public Student(int studentID, string name)
{
StudentID = studentID;
Name = name;
Grade = 1;
}
}
  • 有建構子就不能使用系統預設建構子

Powered by Hexo and Hexo-theme-hiker

Copyright © 2013 - 2020 CYC'S BLOG All Rights Reserved.

UV : | PV :