[英]What is the difference between with and without () symbol in creating an instance of an object in C#?
I have a class Product我有一个 class产品
public class Product
{
public string Name { get; set; }
}
Could you please help me to explain the difference between two case of creating the instance of Product class below?您能否帮我解释一下创建下面的Product class 实例的两种情况之间的区别?
var instanceOne = new Product
{
Name = "iPhone 4"
}
and和
var instanceTwo = new Product()
{
Name = "iPhone 5"
}
Thanks谢谢
There is no difference, they're the same (assuming you meant to initialize the Name
property, not define it, and it can't be static), except for one very specific case:没有区别,它们是相同的(假设您要初始化Name
属性,而不是定义它,并且它不能是静态的),除了一种非常特殊的情况:
Product instanceOne = new()
{
Name = "arf"
};
If you use type-targetted new
, you have to use the new() {...}
version, because new {...}
defines an anonymous type instead.如果您使用以类型为目标的new
,则必须使用new() {...}
版本,因为new {...}
定义了一个匿名类型。
The ()
is redundant in the following example: ()
在以下示例中是多余的:
var instanceTwo = new Product()
{
Name = "iPhone 5"
}
You can just write:你可以写:
var instanceTwo = new Product // <----- () deleted
{
Name = "iPhone 5"
}
There is no difference between these two.这两者之间没有区别。
Please note that object initalisers allow specifying constructor parameters too.请注意object 初始化程序也允许指定构造函数参数。
class Cat
{
public Cat() {}
public Cat(string name) { Name = name; }
public string Name { get; set; }
public string Color { get; set; }
}
(...)
var lightning = new Cat(Name: "Lightning")
{
Color = "White"
};
var storm = new Cat
{
Name = "Storm",
Color = "Gray"
};
Please also note that另请注意
var storm = new Cat
{
Name = "Storm",
Color = "Gray"
};
is not the same as不一样
var storm = new Cat();
storm.Name = "Storm";
storm.Color = "Gray";
The former results in:前者导致:
var __a = new Cat();
__a.Name = "Storm";
__a.Color = "Gray";
var storm = __a;
as shown in Overview of C# 3.0 .如C# 3.0 概述中所示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.