所有可能的数组初始化语法
C# 可以使用的所有数组初始化语法有哪些?
What are all the array initialization syntaxes that are possible with C#?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
C# 可以使用的所有数组初始化语法有哪些?
What are all the array initialization syntaxes that are possible with C#?
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(21)
这些是简单数组的当前声明和初始化方法。
请注意,还存在其他获取数组的技术,例如
IEnumerable
上的 LinqToArray()
扩展。另请注意,在上面的声明中,前两个可以将左侧的
string[]
替换为var
(C# 3+),因为右侧的信息就足够了推断正确的类型。第三行必须按照显示的方式编写,因为单独的数组初始化语法不足以满足编译器的要求。第四种也可以使用推理。第五行在 C# 12 中作为集合表达式引入,其中无法推断目标类型。它还可用于跨度和列表。如果您喜欢整个简洁性,上面的内容可以写成These are the current declaration and initialization methods for a simple array.
Note that other techniques of obtaining arrays exist, such as the Linq
ToArray()
extensions onIEnumerable<T>
.Also note that in the declarations above, the first two could replace the
string[]
on the left withvar
(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. The fifth line was introduced in C# 12 as collection expressions where the target type cannot be inferenced. It can also be used for spans and lists. If you're into the whole brevity thing, the above could be written asC# 中作为表达式的数组创建语法是:
在第一个语法中,大小可以是任何非负整数值,并且数组元素被初始化为默认值。
在第二个中,大小必须是常量,并且给定的元素数量必须匹配。必须存在从给定元素到给定数组元素类型的隐式转换。
在第三种中,元素必须可隐式转换为元素类型,并且大小由给定元素的数量确定。
在第四个中,通过计算所有具有类型的给定元素的最佳类型(如果有)来推断数组元素的类型。所有元素都必须可隐式转换为该类型。大小由给定元素的数量确定。此语法是在 C# 3.0 中引入的。
还有一种只能在声明中使用的语法:
元素必须可以隐式转换为元素类型。大小由给定元素的数量确定。
我建议您参考 C# 4.0 规范,第 7.6.10.4 节“数组创建表达式”。
The array creation syntaxes in C# that are expressions are:
In the first one, the size may be any non-negative integral value and the array elements are initialized to the default values.
In the second one, the size must be a constant and the number of elements given must match. There must be an implicit conversion from the given elements to the given array element type.
In the third one, the elements must be implicitly convertible to the element type, and the size is determined from the number of elements given.
In the fourth one the type of the array element is inferred by computing the best type, if there is one, of all the given elements that have types. All the elements must be implicitly convertible to that type. The size is determined from the number of elements given. This syntax was introduced in C# 3.0.
There is also a syntax which may only be used in a declaration:
The elements must be implicitly convertible to the element type. The size is determined from the number of elements given.
I refer you to C# 4.0 specification, section 7.6.10.4 "Array Creation Expressions".
非空数组
var data0 = new int[3]
var data1 =新 int[3] { 1, 2, 3 }
var data2 = 新int[] { 1, 2, 3 }
var data3 = new[ ] { 1, 2, 3 }
var data4 = { 1, 2, 3 }
不可编译。请改用int[] data5 = { 1, 2, 3 }
。空数组
var data6 = new int[0]
var data7 = new int[] { }
var data8 = new [] { }
和int[] data9 = new [] { }
不可编译。var data10 = { }
不可编译。请改用int[] data11 = { }
。作为方法的参数
只有可以使用
var
关键字指定的表达式才能作为参数传递。Foo(new int[2])
Foo(new int[2] { 1, 2 })
Foo(new int[] { 1, 2 })
Foo(new[] { 1, 2 })
Foo({ 1, 2 })
不可编译Foo(new int[0] )
Foo(new int[] { })
Foo({})
不可编译Non-empty arrays
var data0 = new int[3]
var data1 = new int[3] { 1, 2, 3 }
var data2 = new int[] { 1, 2, 3 }
var data3 = new[] { 1, 2, 3 }
var data4 = { 1, 2, 3 }
is not compilable. Useint[] data5 = { 1, 2, 3 }
instead.Empty arrays
var data6 = new int[0]
var data7 = new int[] { }
var data8 = new [] { }
andint[] data9 = new [] { }
are not compilable.var data10 = { }
is not compilable. Useint[] data11 = { }
instead.As an argument of a method
Only expressions that can be assigned with the
var
keyword can be passed as arguments.Foo(new int[2])
Foo(new int[2] { 1, 2 })
Foo(new int[] { 1, 2 })
Foo(new[] { 1, 2 })
Foo({ 1, 2 })
is not compilableFoo(new int[0])
Foo(new int[] { })
Foo({})
is not compilable将创建重复“count”次的空字符串数组。如果您想使用相同但特殊的默认元素值初始化数组。小心引用类型,所有元素都将引用同一个对象。
Will create array of empty strings repeated 'count' times. In case you want to initialize array with same yet special default element value. Careful with reference types, all elements will refer same object.
如果您想初始化预先初始化的相等(非
null
或default
之外的元素)元素的固定数组,请使用以下内容:另请参加 此讨论。
In case you want to initialize a fixed array of pre-initialized equal (non-
null
or other thandefault
) elements, use this:Also please take part in this discussion.
创建自定义类数组的示例
下面是类定义。
这是初始化数组的方法:
Example to create an array of a custom class
Below is the class definition.
This is how you can initialize the array:
请注意
以下数组:
将编译为:
Just a note
The following arrays:
Will be compiled to:
不使用LINQ重复:
Repeat without LINQ:
或
或和
多维数组中的
or
or
and in multi dimensional array
在 C# 12 中,您将能够创建如下数组: int[] Positions = [1, 2, 3];
真的很棒!
In C# 12, you will able to create an array like this : int[] positions = [1, 2, 3];
Really great !
创建和初始化对象数组的另一种方法。这与 @Amol 上面发布的示例类似,只不过这个示例使用了构造函数。一丝多态性洒入其中,我无法抗拒。
上下文类:
Another way of creating and initializing an array of objects. This is similar to the example which @Amol has posted above, except this one uses constructors. A dash of polymorphism sprinkled in, I couldn't resist.
Classes for context:
您好,只是添加另一种方式:
从这个页面:
https://learn. microsoft.com/it-it/dotnet/api/system.linq.enumerable.range?view=netcore-3.1
如果您想生成指定范围内的整数序列,您可以使用此表单范围 strat 0 到 9:
hi just to add another way:
from this page :
https://learn.microsoft.com/it-it/dotnet/api/system.linq.enumerable.range?view=netcore-3.1
you can use this form If you want to Generates a sequence of integral numbers within a specified range strat 0 to 9:
从 C# 12 开始,您现在还可以使用 集合表达式。请注意扩展运算符
..
,它将采用IEnumerable
并将其项目展平到集合表达式中。一些示例:仅一个元素
100 个元素,其中每个元素代表其索引
由 12 个元素组成的数组,其中第一个和最后一个值为 1,其余为 0
请注意,集合表达式不仅限于数组,还可以用于构造许多不同类型的集合,包括通常不可构造的集合(例如接口和 Span):
As of C# 12, you can now also initialize arrays with collection expressions. Note the spread operator
..
, which will take anIEnumerable
and flatten its items inside a collection expression. Some examples:Just a single element
100 elements where each element represents its index
An array of 12 elements where the first and last values are 1 and the rest are 0
Note that collection expressions are not exclusive to arrays and can be used to construct many different types of collections, including those not typically constructable (like interfaces and
Span
):对于下面的类:
您可以如下初始化上述对象的数组。
希望这有帮助。
For the class below:
you can initialize the array of above object as below.
Hope this helps.
您还可以创建动态数组,即您可以在创建数组之前首先询问用户数组的大小。
You can also create dynamic arrays i.e. you can first ask the size of the array from the user before creating it.
带表达式的简单解决方案。请注意,使用 NewArrayInit 只能创建一维数组。
Trivial solution with expressions. Note that with NewArrayInit you can create just one-dimensional array.
要初始化一个空数组,它应该是 dotnet 5.0
对于字符串
对于数字
To initialize an empty array, it should be
Array.Empty<T>()
in dotnet 5.0For string
For number
另一种方法是调用静态函数(对于静态对象)或实例对象的任何函数。这可用于成员初始化。
现在我还没有测试所有这些,所以我将把我测试过的内容(静态成员和静态函数)放在
我想知道的是是否有一种方法可以绕过函数声明。我知道在这个例子中它可以直接使用,但假设该函数稍微复杂一点并且不能简化为单个表达式。
我想象类似下面的东西(但它不起作用)
基本上是一种仅声明填充变量范围的函数的方法。
如果有人能告诉我如何做到这一点,我会很高兴。
Another way is by calling a static function (for a static object) or any function for instance objects. This can be used for member initialisation.
Now I've not tested all of this so I'll put what I've tested (static member and static function)
What I'd love to know is if there is a way to bypass the function declaration. I know in this example it could be used directly, but assume the function is a little more complex and can't be reduced to a single expression.
I imagine something like the following (but it doesn't work)
Basically a way of just declaring the function for the scope of filling the variable.
I'd love it if someone can show me how to do that.
对于C#中的多维数组声明&赋值。
For multi-dimensional array in C# declaration & assign values.