为什么不能将数组初始化语法与数组声明分开使用? [英] Why can't I use array initialisation syntax separate from array declaration?

查看:76
本文介绍了为什么不能将数组初始化语法与数组声明分开使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以用一个整数来做到这一点:

I can do this with an integer:

int a;
a = 5;

但是我不能用整数数组做到这一点:

But I can't do this with an integer array:

int[] a;
a = { 1, 2, 3, 4, 5 };

为什么不呢?

我没有在寻找正确的语法。我可以查一下。我知道这可行:

To clarify, I am not looking for the correct syntax. That I can look up. I know that this works:

int[] a = { 1, 2, 3, 4, 5 };

相当于:

int a = 5;

我想了解的是,为什么代码对数组失败?代码未能被识别为有效的原因是什么?

What I am trying to understand is, why does the code fail for arrays? What is the reason behind the code failing to be recognised as valid.

推荐答案

之所以存在差异,是因为Microsoft的人们决定在声明时简化语法。并且在同一条语句中初始化数组,但没有添加所需的语法以允许您稍后向其分配新数组。

The reason there is a difference is that the folks at Microsoft decided to lighten the syntax when declaring and initializing the array in the same statement, but did not add the required syntax to allow you to assign a new array to it later.

这就是它起作用的原因:

This is why this works:

int[] a = { 1, 2, 3, 4, 5 };

但这不是:

int[] a;
a = { 1, 2, 3, 4, 5 };

他们是否可以添加语法以允许这样做?当然可以,但是他们没有。他们很可能认为这个用例很少使用,因此不保证优先使用其他功能。 所有新功能都以负100分开头,而这可能只是没有t在优先级列表上的排名足够高。

Could they have added the syntax to allow this? Sure, but they didn't. Most likely they felt that this usecase is so seldom used that it doesn't warrant prioritizing over other features. All new features start with minus 100 points and this probably just didn't rank high enough on the priority list.

请注意, {1,2,3,4,5} 本身没有任何意义,它只能出现在两个地方:

Note that { 1, 2, 3, 4, 5 } by itself has no meaning, it can only appear in two places:


  • 作为数组变量声明的一部分:

  • As part of an array variable declaration:

int[] a = { 1, 2, 3, 4, 5 };


  • 作为数组创建表达式的一部分:

  • As part of an array creation expression:

    new int[] { 1, 2, 3, 4, 5 }
    


  • 数字 5 在C#中随处可见,这就是为什么这样的原因:

    The number 5, on the other hand, has a meaning everywhere it appears in C#, which is why this works:

    int a;
    a = 5;
    

    因此,这只是C#设计师决定支持的特殊语法,仅此而已。

    So this is just special syntax the designers of C# decided to support, nothing more.

    此语法在C#规范的 12.6数组初始化程序

    这篇关于为什么不能将数组初始化语法与数组声明分开使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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