C# - 对象初始化语法

本文关键字:语法 初始化 对象 | 更新日期: 2023-09-12 17:38:45

C# 3.0 (.NET 3.5) 引入了对象初始值设定项语法,这是一种初始化类或集合对象的新方法。对象初始值设定项允许您在创建对象时为字段或属性赋值,而无需调用构造函数。

Example: Object Initializer Syntax

public class Student
{
    public int StudentID { get; set; }
    public string StudentName { get; set; }
    public int Age { get; set; }
    public string Address { get; set; }
}
class Program
{
    static void Main(string[] args)
    {
        Student std = new Student() { StudentID = 1, 
                                      StudentName = "Bill", 
                                      Age = 20, 
                                      Address = "New York"   
                                    };
    }
}

在上面的示例中,学生类是在没有任何构造函数的情况下定义的。 在 Main() 方法中,我们创建了 Student 对象,并同时为大括号中的所有或部分属性赋值。这称为对象初始值设定项语法。

编译器将上述初始值设定项编译为如下所示的内容。

Example: Object Initializer Syntax at Compile time

Student __student = new Student();
__student.StudentID = 1;
__student.StudentName = "Bill";
__student.Age = 20;
__student.StandardID = 10;
__student.Address = "Test";
Student std = __student;

集合初始值设定项语法

集合的初始化方式与使用集合初始值设定项语法的类对象相同。

Example: Object initializer Syntax

var student1 = new Student() { StudentID = 1, StudentName = "John" };
var student2 = new Student() { StudentID = 2, StudentName = "Steve" };
var student3 = new Student() { StudentID = 3, StudentName = "Bill" } ;
var student4 = new Student() { StudentID = 3, StudentName = "Bill" };
var student5 = new Student() { StudentID = 5, StudentName = "Ron" };
IList<Student> studentList = new List<Student>() { 
                                                    student1, 
                                                    student2, 
                                                    student3, 
                                                    student4, 
                                                    student5 
                                                };

还可以同时初始化集合和对象。

Example: Collection initializer Syntax

IList<Student> studentList = new List<Student>() { 
                    new Student() { StudentID = 1, StudentName = "John"} ,
                    new Student() { StudentID = 2, StudentName = "Steve"} ,
                    new Student() { StudentID = 3, StudentName = "Bill"} ,
                    new Student() { StudentID = 3, StudentName = "Bill"} ,
                    new Student() { StudentID = 4, StudentName = "Ram" } ,
                    new Student() { StudentID = 5, StudentName = "Ron" } 
                };

您还可以将 null 指定为元素:

Example: Collection initializer Syntax

IList<Student> studentList = new List<Student>() { 
                                    new Student() { StudentID = 1, StudentName = "John"} ,
                                    null
                                };

初始值设定项的优点

  • 初始值设定项语法使代码更具可读性,易于将元素添加到集合中。
  • 在多线程中很有用。