在创建新的类实例时使用大括号

时间:2017-05-10 15:27:57

标签: c#

我在代码中看到使用大括号在创建新实例时直接通知相关类的变量值。

例子(请参阅employee3)

class Program
{
    static void Main(string[] args)
    {
        //I KNOW THIS.
        //Employee employee1 = new Employee(100, "Mike", 2000, 3);

        //I ALSO KNOW THIS.
        Employee employee2 = new Employee();
            employee2.ID = 101;
            employee2.Name = Henry;
            employee2.Salary = 3000;
            employee2.Experience = 4;

        //BUT THIS IS THE FIRST TIME I HAVE SEEN THIS.
        Employee employee3 = new Employee()
            { ID = 102, Name = "John", Salary = 3000, Experience = 5 };
    }


class Employee
{
    //Employee(iD, name, salary, experience)
    //{
    //    ID = iD;
    //    Name = name;
    //    Salary = salary;
    //    Experience = experience;
    //}

    //Employee() { }

    public int ID { get; set; }
    public string Name { get; set; }
    public int Salary { get; set; }
    public int Experience { get; set; }
}

这些括号是什么意思,它们被称为什么,它们是否有用......

1 个答案:

答案 0 :(得分:1)

它们用于初始化Employee对象实例上的字段。

https://docs.microsoft.com/en-us/dotnet/articles/csharp/programming-guide/classes-and-structs/object-and-collection-initializers

  

对象初始值设定项允许您为任何可访问的字段或值分配值   创建时对象的属性,而不必调用   构造函数后跟赋值语句行。