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

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

问题描述

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<T>上的Linq ToArray()扩展名.

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

还要注意,在上面的声明中,前两个可以用var(C#3+)替换左侧的string[],因为右侧的信息足以推断正确的类型.第三行必须按显示方式编写,因为仅数组初始化语法不足以满足编译器的要求.第四个也可以使用推论.因此,如果您全神贯注,上面的内容可以写为

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天全站免登陆