【问题标题】:Using braces when creating a new class instance [duplicate]创建新类实例时使用大括号[重复]
【发布时间】:2017-05-10 15:27:57
【问题描述】:

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

示例(参见员工 3)

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; }
}

这些大括号是什么意思,它们叫什么,它们在其他方面是否有用...

【问题讨论】:

  • 你是叫大括号括号吗?它被称为对象初始化器。它们也可用于初始化集合:var x = new List<int> { 0, 2, 4 };
  • 该语法称为“对象初始化语法”。
  • 这是完全相同操作的另一种语法。别担心。 A a = new A(); a.field = 1; 可以写成A a = new A() { field=1 } 你可以阅读一下here
  • 好的,谢谢各位,我去查一下。
  • 即使你使用的是c# 6,你也可以在类定义csharp.today/c-6-features-auto-property-initializers中初始化属性

标签: c#


【解决方案1】:

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

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

对象初始值设定项让您可以将值分配给任何可访问的字段或 在创建时对象的属性,而无需调用 构造函数后跟赋值语句行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-10
    • 1970-01-01
    相关资源
    最近更新 更多