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

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

问题描述

什么是所有可能的数组初始化语法这是可能的C#?

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

它变得非常混乱知道,如果它是一个数组初始化或单独的声明。

It gets really confusing to know if it is an array initializer or a separate declaration.

注:我搜索MSDN,GOOGLE了它,但没有一个全功能于一身的指南

Note: I've searched MSDN, googled it, but there isn't an all-in-one guide.

我使用.NET 3.5和C#。

I'm using .NET 3.5 and 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

请注意获取的其他技术阵列存在,如LINQ的 ToArray的()扩展了IEnumerable< T>

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

另外请注意,在上面的声明中,前两个可以取代的String [] 左侧用 VAR (C#3 +),作为右边的信息,就足以推断正确的类型。第三行必须写成显示出来,单独数组初始化语法是不够的,满足编译器的需求。所以,如果你到整个简洁的东西,上面可以写成

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

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

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