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

问题描述

我最近看过这两件事情,我有点糊涂了。

I've seen these two things lately and I'm a bit confused.

var blah = new MyClass() { Name = "hello" }

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

推荐答案

据我所知,他们是完全等价的。 C#的规范(或至少微软的实现它),您可以省略()使用默认构造函数(无参数)时,只要你使用大括号(即语法的的)。请注意,对象初始化,使这里的构造函数没有区别 - 新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.

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

08-01 07:39