61 .net c# instantiation
我只是注意到在构造对象时使用{}而不是()给出相同的结果.
class Customer
{
public string name;
public string ID {get; set;}
}
static void Main()
{
Customer c1= new Customer{}; //Is this a constructor?
Customer c2= new Customer();
//what is the concept behind the ability to assign values for properties
//and fields inside the {} and is not allowable to do it inside ()
//without defining a constructor:
Customer c3= new Customer{name= "John", ID="ABC"};
}
Run Code Online (Sandbox Code Playgroud)
是否{}像()建立在C#中的新对象时?
Jon*_*eet 107
在C#中有三种直接创建新对象的方法:
带参数列表的简单构造函数调用:
new Foo() // Empty argument list
new Foo(10, 20) // Passing arguments
Run Code Online (Sandbox Code Playgroud)带有参数列表的对象初始值设定项
new Foo() { Name = "x" } // Empty argument list
new Foo(10, 20) { Name = "x" } // Two arguments
Run Code Online (Sandbox Code Playgroud)没有参数列表的对象初始值设定项
new Foo { Name = "x" }
Run Code Online (Sandbox Code Playgroud)最后一个表单完全等同于指定一个空参数列表.通常它会调用无参数构造函数,但它可以调用一个构造函数,其中所有参数都有默认值.
现在,在这两个对象初始化的例子,我已经给了,我给自己定一个Name属性-你可以设置其他属性/字段,或者甚至设置没有属性和字段.所以这三个都是等价的,实际上没有传递构造函数参数并且没有指定要设置的属性/字段:
new Foo()
new Foo() {}
new Foo {}
Run Code Online (Sandbox Code Playgroud)
其中,第一个是最常规的.
您可以使用对象初始值设定项以声明方式初始化类型对象,而无需显式调用该类型的构造函数.
https://msdn.microsoft.com/en-us/library/bb397680.aspx
如果类型具有默认构造函数,也可以省略调用构造函数.所以
Customer c1 = new Customer { };
Run Code Online (Sandbox Code Playgroud)
与...完全相同
Customer c1 = new Customer() { };
Run Code Online (Sandbox Code Playgroud)