所有可能的数组初始化语法 [英] All possible array initialization syntaxes

查看:24
本文介绍了所有可能的数组初始化语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C# 可以使用的所有数组初始化语法是什么?

What are all the array initialization syntaxes that are possible with C#?

推荐答案

这些是简单数组的当前声明和初始化方法.

These are the current declaration and initialization methods for a simple array.

string[] array = new string[2]; // creates array of length 2, default values
string[] array = new string[] { "A", "B" }; // creates populated array of length 2
string[] array = { "A" , "B" }; // creates populated array of length 2
string[] array = new[] { "A", "B" }; // created populated array of length 2

请注意,还存在其他获取数组的技术,例如 IEnumerable 上的 Linq ToArray() 扩展.

Note that other techniques of obtaining arrays exist, such as the Linq ToArray() extensions on IEnumerable<T>.

还要注意,在上面的声明中,前两个可以用 var (C# 3+) 替换左边的 string[],作为关于right 足以推断正确的类型.第三行必须按照显示的方式编写,因为单独的数组初始化语法不足以满足编译器的要求.第四个也可以使用推理.所以,如果你对整个简洁性感兴趣,上面可以写成

Also note that in the declarations above, the first two could replace the string[] on the left with var (C# 3+), as the information on the right is enough to infer the proper type. The third line must be written as displayed, as array initialization syntax alone is not enough to satisfy the compiler's demands. The fourth could also use inference. So if you're into the whole brevity thing, the above could be written as

var array = new string[2]; // creates array of length 2, default values
var array = new string[] { "A", "B" }; // creates populated array of length 2
string[] array = { "A" , "B" }; // creates populated array of length 2
var array = new[] { "A", "B" }; // created populated array of length 2 

这篇关于所有可能的数组初始化语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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