什么是这两个数组声明之间的区别? [英] What is difference between these two array declarations?
问题描述
看来这两个声明是一样的:
It seems these two declarations are the same:
int[] array1 = {11, 22, 33};
和
int[] array2 = new int[] {11, 22, 33};
但什么是这部分新INT [] $的需要C $ C>第二个样本中?结果
这会让区别?
But what is the need of this part new int[]
in the second sample?
Does it make difference?
推荐答案
有在无差异这种情况下 - 但是第一个语法的只有可用声明变量时。从C#4规格12.6节:
There's no difference in this case - but the first syntax is only available when declaring a variable. From the C# 4 spec section 12.6:
数组初始化函数可以在域声明,局部变量声明和数组创建表达式来指定
Array initializers may be specified in field declarations, local variable declarations, and array creation expressions.
(将数组初始化是在括号中的位 - 和一个数组创建表达式中可指定表格新的INT []
或什么的。)
(The "array initializer" is the bit in braces - and an array creation expression is the form where you specify new int[]
or whatever.)
当你不声明一个局部变量或字段(例如,如果你传递一个参数的方法),你必须使用第二种形式,或者从C#3.0,你可以使用隐式类型数组:
When you're not declaring a local variable or a field (e.g. if you're passing an argument to a method) you have to use the second form, or from C# 3.0 you can use an implicitly typed array:
Foo(new[] { 1, 2, 3} );
这篇关于什么是这两个数组声明之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!