📜  C#3.0 对象和集合初始化器(object/collection initializer)

📅  最后修改于: 2020-11-01 03:02:50             🧑  作者: Mango

C#对象初始化器

C#对象初始化程序是在对象创建时分配值的新方法。它不需要构造函数调用来分配字段值。对象初始化器用大括号括起来,值用逗号分隔。

在下面的示例中,我们使用对象初始化程序分配值。

C#对象初始化器示例

using System;
namespace CSharpFeatures
{
    class Student
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
    }
    class ObjectInitializer
    {
        public static void Main(string[] args)
        {
            // Using Object Initialilzer
            Student student = new Student { ID=101, Name="Rahul", Email="rahul@example.com" };
            // Displaying Initialized Values
            Console.WriteLine(student.ID);
            Console.WriteLine(student.Name);
            Console.WriteLine(student.Email);
        }
    }
}

输出:

101
Rahul
rahul@example.com

C#集合初始化器

集合初始化器使我们可以初始化实现IEnumerable接口的集合类型。以下示例实现了集合初始化器。

C#集合初始化器示例

using System;
using System.Collections.Generic;
namespace CSharpFeatures
{
    class Student
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
    }
    class ObjectInitializer
    {
        public static void Main(string[] args)
        {
            List students = new List {
                new Student { ID=101, Name="Rahul", Email="rahul@example.com" },
                new Student { ID=102, Name="Peter", Email="peter@abc.com" },
                new Student { ID=103, Name="Irfan", Email="irfan@example.com" }
            };
            foreach (Student student in students)
            {
                Console.Write(student.ID+" ");
                Console.Write(student.Name+" ");
                Console.Write(student.Email+" ");
                Console.WriteLine();
            }
        }
    }
}

输出:

101 Rahul rahul@example.com
102 Peter peter@abc.com
103 Irfan irfan@example.com