圆括号还是不是?有什么不同? [英] Round brackets or not? Whats the difference?

查看:135
本文介绍了圆括号还是不是?有什么不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近看过这两件事,我有点困惑。

  var blah = new MyClass {Name =hello} 

  var blah = new MyClass {Name =hello} 

有什么区别?

更新:
这是否意味着如果我在一个构造函数中有一些计算我必须调用第一个

解决方案

据我所知,他们完全相同。 C#规范(或者至少Microsoft的实现)允许你在使用默认构造函数(无参数)时省略(),只要你使用大括号(即 object initialisers )。注意,对象初始化器对这里的构造函数没有区别 - new MyClass 位仍然被单独解释为对默认构造函数的调用。就个人而言,我建议您在没有对象初始化程序时,始终包含圆括号()以保持一致性 - 需要。


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??

解决方案

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.

这篇关于圆括号还是不是?有什么不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆