Menu
CoddyTech

构造函数

本课属于 Coddy C# 学习旅程的“面向对象编程”单元。第 7 课,共 70 课。

构造函数是一种特殊的方法,在你创建对象时运行。它会初始化对象的属性和字段。

没有参数的默认构造函数

public class Book
{
    public string Title { get; set; }
    public string Author { get; set; }
    
    // 默认构造函数
    public Book()
    {
        Title = "Unknown";
        Author = "Unknown";
    }
}

带参数的构造函数

public class Book
{
    public string Title { get; set; }
    public string Author { get; set; }
    
    // 带参数的构造函数
    public Book(string title, string author)
    {
        Title = title;
        Author = author;
    }
}

构造函数重载:多个构造函数

public class Book
{
    public string Title { get; set; }
    public string Author { get; set; }
    public int Pages { get; set; }
    
    // 带两个参数的构造函数
    public Book(string title, string author)
    {
        Title = title;
        Author = author;
        Pages = 0;
    }
    
    // 带三个参数的构造函数
    public Book(string title, string author, int pages)
    {
        Title = title;
        Author = author;
        Pages = pages;
    }
}

使用 this 链接构造函数

public class Book
{
    public string Title { get; set; }
    public string Author { get; set; }
    public int Pages { get; set; }
    
    // 主构造函数
    public Book(string title, string author, int pages)
    {
        Title = title;
        Author = author;
        Pages = pages;
    }
    
    // 使用默认页数调用主构造函数
    public Book(string title, string author) : this(title, author, 0)
    {
    }
}

使用不同的构造函数创建对象

Book book1 = new Book("1984", "George Orwell");
Book book2 = new Book("Harry Potter", "J.K. Rowling", 500);

构造函数与类同名,并且没有返回类型。使用 new 关键字时,它们会自动运行。你可以定义多个参数不同的构造函数(重载)。

challenge icon

挑战

中等

使用构造函数重载和链接,为 Product 类创建 3 个构造函数:

  • 包含 3 个参数的构造函数:name、price 和 stock
  • 包含 2 个参数的构造函数:name 和 price(stock 默认为 0)
  • 不带参数的默认构造函数(name = "Unknown",price = 0,stock = 0)

使用 this 进行构造函数链接,避免代码重复。

亲手试试

using System;

class Program
{
    static void Main()
    {
        string name = Console.ReadLine();
        decimal price = decimal.Parse(Console.ReadLine());
        int stock = int.Parse(Console.ReadLine());
        
        Product product1 = new Product(name, price, stock);
        Product product2 = new Product();
        Product product3 = new Product("Keyboard", 79.99m);
        
        Console.WriteLine($"Product 1: {product1.Name} - ${product1.Price} (Stock: {product1.Stock})");
        Console.WriteLine($"Product 2: {product2.Name} - ${product2.Price} (Stock: {product2.Stock})");
        Console.WriteLine($"Product 3: {product3.Name} - ${product3.Price} (Stock: {product3.Stock})");
    }
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向对象编程中的所有课

自己练习: C# 在线编译器