不同类型的对象初始化
你好 之间是否有什么区别
MyClass calass = new MyClass()
{
firstProperty = "text",
secondProperty = "text"
}
我想知道这样的初始化对象和这样的初始化对象
MyClass calass = new MyClass // no brackets
{
firstProperty = "text",
secondProperty = "text"
}
我也想知道这种初始化的名称是什么
Hi
I was wondering if there is any difference between initializing object like this
MyClass calass = new MyClass()
{
firstProperty = "text",
secondProperty = "text"
}
and initializaing object like this
MyClass calass = new MyClass // no brackets
{
firstProperty = "text",
secondProperty = "text"
}
I was also wondering what is the name of this kind of initialization
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,绝对没有区别。在这两种情况下,您都使用对象初始值设定项表达式。对象初始值设定项是在 C# 3 中引入的。
在这两种情况下,这完全等同于:
请注意对
calass
的赋值仅在属性被赋值之后发生 - 就像您一样期望从源代码中得到。 (在某些情况下,我相信 C# 编译器可以有效地删除额外的变量并重新排列分配,但它必须明显表现得像这个翻译。如果您重新分配现有的变量,它肯定会产生影响变量。)编辑:关于省略构造函数参数的细微之处。如果这样做,它总是相当于包含一个空参数列表 - 但这与调用无参数构造函数不同。例如,可以有可选参数,或参数数组:
Nope, absolutely no difference. In both cases you're using an object initializer expression. Object initializers were introduced in C# 3.
In both cases, this is exactly equivalent to:
Note how the assignment to
calass
only happens after the properties have been assigned - just as you'd expect from the source code. (In some cases I believe the C# compiler can effectively remove the extra variable and rearrange the assignments, but it has to observably behave like this translation. It can certainly make a difference if you're reassigning an existing variable.)EDIT: Slight subtle point about omitting constructor arguments. If you do so, it's always equivalent to including an empty argument list - but that's not the same as being equivalent to calling the parameterless constructor. For example, there can be optional parameters, or parameter arrays:
没有。事实上,ReSharper 会抱怨带有初始化器的无参数构造函数的括号是多余的。如果您使用带有一个或多个参数的构造函数,您(显然)仍然需要它们,但由于情况并非如此,只需删除它们即可。
Nope. In fact, ReSharper would complain that the brackets of a parameterless constructor with initializer are redundant. You would (obviously) still need them if you were using a constructor with one or more parameters, but since this isn't the case just remove them.