this關鍵字
- 代表當前類別的對象
- 在類別當中顯示的調用本類別的構造函數
:this
:thiscall本身類別的其他的構造函式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class Student
{
//構造函式
public Student(string name, int age, char gender, int english, int math)
{
this.Name = name;
this.Age = age;
this.Gender = gender;
this.English = english;
this.Math = math;
}
public Student(string name, int english, int math)
: this(name, 18, 'C', english, math)
{
// : this(name, 18, 'C', english, math)會調用的是有全部屬性的參數
//這邊↓↓↓就算沒沒寫也可以運行
//this.Name = name;
//this.English = english;
//this.Math = math;
}
public Student(string name, int age, char gender)
{
this.Name = name;
this.Age = age;
this.Gender = gender;
}
}
範例::this&:base
:this調用自己的構造函數:base調用父類的構造函數
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/// <summary>
/// 商品的父類
/// </summary>
internal class ProductFather
{
public string ID { get; set; } //Guid.NewGuid()
public string Name { get; set; }
public decimal Price { get; set; }
public int Count { get; set; }
public ProductFather(string id, string name, decimal price, int count)
{
this.ID = id;
this.Name = name;
this.Price = price;
this.Count = count;
}
public ProductFather(string id, string name, decimal price)
: this(id, name, price, count: 0) //:this調用自己的構造函數
{
}
}
/// <summary>
/// Acer筆電 子類
/// </summary>
internal class Acer : ProductFather {
public Acer(string id, string name, decimal price)
: base(id, name, price) //:base調用父類的構造函數
{
}
}