对象初始化器
本课属于 Coddy C# 学习旅程的“面向对象编程”单元。第 8 课,共 70 课。
对象初始化器提供了一种便捷的方式,可以在创建对象时设置属性值,而不必调用带有许多参数的构造函数。
使用构造函数的传统方式
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public string City { get; set; }
}
Person person = new Person();
person.Name = "Alice";
person.Age = 25;
person.City = "New York";使用对象初始化器语法
Person person = new Person
{
Name = "Alice",
Age = 25,
City = "New York"
};使用构造函数的对象初始化器
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public string City { get; set; }
public Person(string name)
{
Name = name;
}
}
// 构造函数设置 Name,初始化器设置其他属性
Person person = new Person("Bob")
{
Age = 30,
City = "London"
};嵌套对象初始化器
public class Address
{
public string Street { get; set; }
public string City { get; set; }
}
public class Person
{
public string Name { get; set; }
public Address Address { get; set; }
}
Person person = new Person
{
Name = "Charlie",
Address = new Address
{
Street = "123 Main St",
City = "Boston"
}
};使用初始化器创建多个对象
Person person1 = new Person { Name = "Alice", Age = 25 };
Person person2 = new Person { Name = "Bob", Age = 30 };
Person person3 = new Person { Name = "Charlie", Age = 35 };对象初始化器能让代码更简洁易读。属性会在构造函数运行后设置。无论构造函数是否有参数,你都可以使用初始化器,这让对象的创建更加灵活简洁。
挑战
中等使用不同的对象初始化方式创建三个 Student 对象:
- student1:使用默认构造函数和对象初始化器,根据输入设置所有属性(Name、StudentId、Major、GPA)
- student2:使用对象初始化器,仅设置 Name = "Bob" 和 Major = "Engineering"
- student3:使用 "Charlie" 作为参数调用构造函数,然后使用对象初始化器设置 StudentId = 54321、Major = "Mathematics"、GPA = 3.5
亲手试试
using System;
class Program
{
static void Main()
{
string name = Console.ReadLine();
int studentId = int.Parse(Console.ReadLine());
string major = Console.ReadLine();
double gpa = double.Parse(Console.ReadLine());
// TODO:使用对象初始化器创建 student1,并设置所有属性
// 使用默认构造函数,并设置 Name、StudentId、Major 和 GPA
// TODO:使用对象初始化器创建 student2,只设置 Name 和 Major
// 将 Name 设为 "Bob",将 Major 设为 "Engineering"
// TODO:使用 name 参数为 "Charlie" 的构造函数创建 student3
// 然后使用对象初始化器设置 StudentId = 54321、Major = "Mathematics"、GPA = 3.5
Console.WriteLine($"Student 1: {student1.Name} (ID: {student1.StudentId}) - {student1.Major}, GPA: {student1.GPA}");
Console.WriteLine($"Student 2: {student2.Name} (ID: {student2.StudentId}) - {student2.Major}, GPA: {student2.GPA}");
Console.WriteLine($"Student 3: {student3.Name} (ID: {student3.StudentId}) - {student3.Major}, GPA: {student3.GPA}");
}
}这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向对象编程中的所有课
自己练习: C# 在线编译器