圆括号还是不圆括号? 有什么不同?
我最近看到这两件事,我有点困惑。
var blah = new MyClass() { Name = "hello" }
和
var blah = new MyClass { Name = "hello" }
有什么区别? 为什么它们都有效?
更新: 这是否意味着如果我在构造函数中有一些东西做了一些计算,我就必须调用第一个?
I've seen these two things lately and I'm a bit confused.
var blah = new MyClass() { Name = "hello" }
and
var blah = new MyClass { Name = "hello" }
Whats the difference? and why do they both work?
Update:
Does this mean that if i have something in a constructor which does some computation that i would have to call the first one??
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
据我所知,它们完全等效。 C# 规范(或者至少是 Microsoft 的实现)允许您在使用默认构造函数(无参数)时省略 (),只要您使用大括号(即 对象初始值设定项)。 请注意,这里的对象初始值设定项与构造函数没有区别 - new MyClass 位仍然被单独解释为对默认构造函数的调用。 就我个人而言,我建议您始终包含圆括号 () 以保持一致性 - 当您后面没有对象初始值设定项时,您需要它们。
As far as I know, they're exactly equivalent. The C# specification (or at least Microsoft's implementation of it) allows you to omit the () when using the default constructor (no parameters) as long as you're using curly brackets (i.e. the syntax for object initialisers). Note that the object initializer makes no difference to the constructor here - the
new MyClass
bit still gets interpreted separately as a call to the default constructor. Personally, I would recommend you always include the round brackets () for consistency - you need them when you don't have an object initializer following.没有什么区别,第一种形式只是指出您也在调用构造函数:
将导致:
There is no difference, first form just points out that you are also calling the constructor:
will result in:
要添加上述注释,添加额外内容肯定有助于澄清正在调用什么构造函数或 init 方法。 当然还有造型方面......
To add to the above comments, adding extra's definitely help to clarify what constructor or init method is being called. Definitely a styling aspect also....
我猜他们保留了对象初始值设定项的 () 形式,因为有些用户喜欢 () 调用构造函数的清晰性,但 iirc、C++(或第一个版本)允许调用不带括号的构造函数。 我的第二个猜测是,他们(语言设计者)倾向于让 C# 具有类似 JSON 的结构,这有点简洁,因此他们可以方便地调用没有 () 的构造函数。 我赞成第二种形式。
没有什么区别,就像 VB.NET 的属性(尽管很糟糕)允许您以两种形式分配变量:button1.Height = 100 button1.Height() = 1000 如果您可能会问的话,有点蹩脚。
I guess they retain the () form for object initializers because some users like the clarity of () for invoking the constructor, but iirc, C++ (or the first versions) allow invoking constructor without the parentheses. My second guess, they(language designers) are leaning to make C# have JSON-like structure, which is kinda neat, so they facilitate invoking constructor without the (). I favor the second form.
There's no difference, just like the property(though so bad) of VB.NET would allow you to assign variables in two forms: button1.Height = 100 button1.Height() = 1000 Kinda lame, if you may ask.
实际上,除非您处理没有默认空构造函数的类型,否则它们没有太大区别。 在这种情况下,您可以编写类似“new SomeClass(MandatoryArgument) { Prop1 = 1, Prop2 = 2 }”的内容
Actually they don't have much difference until you deal with Types that don't have default empty constructor. In such a case you can get benefit writing something like "new SomeClass(MandatoryArgument) { Prop1 = 1, Prop2 = 2 }"