在C#中从一个构造函数调用另一个构造函数(构造函数链)
大家好!我是一名C#初学者开发者,遇到了一个问题。我有一个`Order`类,其中有几个带不同参数的构造函数。我想避免代码重复,但不知道如何从一个构造函数调用另一个构造函数。
以下是简化代码:
```csharp
public class Order
{
public int Id { get; set; }
public string CustomerName { get; set; }
public decimal Amount { get; set; }
public DateTime CreatedDate { get; set; }
// 构造函数1:所有参数
public Order(int id, string customerName, decimal amount, DateTime createdDate)
{
Id = id;
CustomerName = customerName;
Amount = amount;
CreatedDate = createdDate;
Console.WriteLine("订单已创建:" + id);
}
// 构造函数2:仅ID和姓名,日期为今天
public Order(int id, string customerName)
{
Id = id;
CustomerName = customerName;
Amount = 0; // 默认值