简体   繁体   English

初始化程序语法与无参数构造函数语法

[英]Initializer syntax vs. parameterless constructor syntax

There are two alternative styles of instantiating a new empty "list" -style object: 实例化一个新的空“列表”样式对象有两种替代样式:

var list = new SomeListType<int>();

or 要么

var list = new SomeListType<int> { };

The first relies on allowing the basic constructor to setup the object, the second would seem to also implicitly rely on the constructor, but also specifies an empty initializer list. 第一个依赖于允许基本构造函数设置对象,第二个似乎也隐式依赖于构造函数,但还指定了一个空的初始化列表。

(The intializer list being left empty on purpose, say if it seemed to be more readable or clearer in some context.) (初始化器列表故意留空,例如,在某些情况下它看起来更可读或更清晰。)

Is there any practical or functional difference between these two approaches? 这两种方法之间在实践或功能上有什么区别吗?

(Note -- SomeListType could be anything that can be constructed like this - such as a standard List<T> or some custom class. Using int just for example). (注意SomeListType可以是可以像这样构造的任何东西-例如标准List<T>或某些自定义类。仅以int为例)。

Even the generated IL code will be the same for both options: 对于这两个选项,即使生成的IL代码也将相同:

newobj instance void class Namespace.SomeListType`1<int32>::.ctor() 

So there is no functional difference at all. 因此根本没有功能上的差异。

The two lines you have written will compile the same. 您编写的两行将编译相同。 The difference is that in the second version you can initialize the list by adding items in the curly braces (provided your lists implements the ICollection<T> interface or provides a respective Add method: 区别在于,在第二个版本中,您可以通过在花括号中添加项目来初始化列表(前提是您的列表实现ICollection<T>接口或提供相应的Add方法:

var list = new SomeListType<int> { 1, 2, 3, 4 };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM