C#列表定义,括号与花括号 [英] C# List definition, parentheses vs curly braces

查看:256
本文介绍了C#列表定义,括号与花括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚注意到,当您在c#中声明List时,可以在括号的最后加上括号.

I've just noticed that when you declare a List in c# you can put parentheses or curly braces at the end.

List<string> myList = new List<string>();
List<string> myList2 = new List<string>{};

这两个列表似乎具有相同的功能.用括号或花括号声明它们会导致实际差异吗?

Both these list appear to have the same functionality. Is there any actual difference caused by declaring them with parentheses or curly braces?

推荐答案

使用花括号{ }称为集合初始化器.对于实现IEnumerable的类型,通常会代表您调用Add方法:

The use of curly braces { } is called a collection initializer. For types that implement IEnumerable the Add method would be invoked normally, on your behalf:

List<string> myList2 = new List<string>() { "one", "two", "three" };

允许使用空集合初始值设定项:

Empty collection initializers are allowed:

List<string> myList2 = new List<string>() { };

而且,在实现初始化程序时,可以省略默认构造函数的括号():

And, when implementing an initializer, you may omit the parenthesis () for the default constructor:

List<string> myList2 = new List<string> { };

您可以对类属性执行类似的操作,但随后将其称为对象初始化程序.

You can do something similar for class properties, but then it's called an object initializer.

var person = new Person
                 {
                     Name = "Alice",
                     Age = 25
                 };

还有可能将它们结合起来

And its possible to combine these:

var people = new List<Person>
                 {
                     new Person
                         {
                             Name = "Alice",
                             Age = 25
                         },
                     new Person
                         {
                             Name = "Bob"
                         }
                 };

C#3.0中引入的此语言功能还支持初始化匿名类型,在LINQ查询表达式中特别有用:

This language feature introduced in C# 3.0 also supports initializing anonymous types, which is especially useful in LINQ query expressions:

var person = new { Name = "Alice" };

它们也可以用于数组,但是您可以进一步省略从第一个元素推断出的类型:

They also work with arrays, but you can further omit the type which is inferred from the first element:

var myArray = new [] { "one", "two", "three" };

初始化多维数组的过程如下:

And initializing multi-dimensional arrays goes something like this:

var myArray = new string [,] { { "a1", "b1" }, { "a2", "b2" }, ... };

更新

从C#6.0开始,您还可以使用索引初始化程序.这是一个示例:

Since C# 6.0, you can also use an index initializer. Here's an example of that:

var myDictionary = new Dictionary<string, int>
                       {
                           ["one"] = 1,
                           ["two"] = 2,
                           ["three"] = 3
                       };

这篇关于C#列表定义,括号与花括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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