C# 建構函式
建構函式
建構函式是用於**初始化物件**的**特殊方法**。建構函式的優點是,在建立類物件時會自動呼叫它。它可以用於為欄位設定初始值。
示例
建立建構函式
// Create a Car class
class Car
{
public string model; // Create a field
// Create a class constructor for the Car class
public Car()
{
model = "Mustang"; // Set the initial value for model
}
static void Main(string[] args)
{
Car Ford = new Car(); // Create an object of the Car Class (this will call the constructor)
Console.WriteLine(Ford.model); // Print the value of model
}
}
// Outputs "Mustang"
請注意,建構函式的名稱必須**與類名匹配**,並且它不能有**返回型別**(例如 void
或 int
)。
另外請注意,在建立物件時會呼叫建構函式。
所有類預設都有建構函式:如果您不自己建立類建構函式,C# 會為您建立一個。但是,這樣您就無法為欄位設定初始值。
建構函式節省時間! 檢視此頁面上的最後一個示例,以真正理解原因。
構造方法引數
建構函式也可以接受引數,這用於初始化欄位。
以下示例向建構函式添加了一個 string modelName
引數。在建構函式內部,我們將 model
設定為 modelName
(model=modelName
)。當我們呼叫建構函式時,我們會向建構函式傳遞一個引數("Mustang"
),這將把 model
的值設定為 "Mustang"
。
示例
class Car
{
public string model;
// Create a class constructor with a parameter
public Car(string modelName)
{
model = modelName;
}
static void Main(string[] args)
{
Car Ford = new Car("Mustang");
Console.WriteLine(Ford.model);
}
}
// Outputs "Mustang"
您可以擁有任意數量的引數
示例
class Car
{
public string model;
public string color;
public int year;
// Create a class constructor with multiple parameters
public Car(string modelName, string modelColor, int modelYear)
{
model = modelName;
color = modelColor;
year = modelYear;
}
static void Main(string[] args)
{
Car Ford = new Car("Mustang", "Red", 1969);
Console.WriteLine(Ford.color + " " + Ford.year + " " + Ford.model);
}
}
// Outputs Red 1969 Mustang
提示: 就像其他方法一樣,可以透過使用不同數量的引數來**過載**建構函式。
建構函式節省時間
當您考慮上一章中的示例時,您會注意到建構函式非常有用,因為它們有助於減少程式碼量。
無建構函式
prog.cs
class Program
{
static void Main(string[] args)
{
Car Ford = new Car();
Ford.model = "Mustang";
Ford.color = "red";
Ford.year = 1969;
Car Opel = new Car();
Opel.model = "Astra";
Opel.color = "white";
Opel.year = 2005;
Console.WriteLine(Ford.model);
Console.WriteLine(Opel.model);
}
}
有建構函式
prog.cs
class Program
{
static void Main(string[] args)
{
Car Ford = new Car("Mustang", "Red", 1969);
Car Opel = new Car("Astra", "White", 2005);
Console.WriteLine(Ford.model);
Console.WriteLine(Opel.model);
}
}