C# - 对象初始化语法 Object Initializer Syntax

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

public class Student
{

    public int Id { get; set; }

    public string Name { get; set; }

    public int Age { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var s1 = new Student()
        {
            Id = 1,
            Name = "Malema.net",
            Age = 100
        };
    }
}

集合初始化语法

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

using System;
using System.Collections.Generic;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            var s1 = new Student()
            {
                Id = 1,
                Name = "Malema.net",
                Age = 100
            };
            var s2 = new Student()
            {
                Id = 2,
                Name = "C#",
                Age = 50
            };
            var students = new List<Student>() { s1, s2 }; //list 需要引用命名空间 using System.Collections.Generic;
        }
    }
}

也可以如下面这个样子

using System;
using System.Collections.Generic;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            var students = new List<Student>()
            {
                new Student()
                {
                    Id = 1,
                    Name = "Malema.net",
                    Age = 100
                },
                new Student()
                {
                    Id = 2,
                    Name = "C#",
                    Age = 50
                },
            };
        }
    }
}

字典的初始化语法

var dict2 = new Dictionary<string, string>()
{
    { "xm" ,"厦门"}, //"xm"是key "厦门"是value
    { "bj" ,"北京"},
    { "sh" ,"上海" },
};

C#6.0 之后 提供的 Index Initializers 索引初始化器

var dict1 = new Dictionary<string, string>()
{
    ["xm"] = "厦门",
    ["bj"] = "北京",
    ["sh"] = "上海",
};
上一篇:C# Path
最近更新的
...