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);
}
}