省略C#转自铁血数组初始化新 [英] Omitting c# new from jagged array initialization

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

问题描述

来源: http://msdn.microsoft.com/en-us/库/ 2s05feca.aspx



注意,你不能省略的元素初始化新的运营商,因为没有为元素没有默认初始化:

  INT [] [] = jaggedArray3 
{
新INT [] {1,3,5,7,9 }
新INT [] {0,2,4,6},
新INT [] {} 11,22
};



这是什么意思?



为什么它是确定在省略新:

  INT [] = arrSimp {1,2,3}; 
INT [,] arrMult = {{1,1},{2,2},{3,3}};



但不可能在:

  INT [] [,] arrJagg = {新的INT [,] {{1,1},新的INT [,] {{2,2},新的INT [,] {{ 3,3}}}; 


解决方案

首先,真巧的一个方面,你的问题是我的博客今天的议题:



http://ericlippert.com/2013/01/24/five-dollar-words-for-programmers-elision/



您已经发现在C#中的表达式进行分类的方式一小瘊子。事实证明,该数组初始化语法 {1,2,3} 不是的表达式的。相反,它是一个只能作为另一个表达式的一部分句法单位:

 新[] {1,2, 3} 
新INT [] {1,2,3}
新INT [3] {1,2,3}
新INT [,] {{1,2,3} }
...等等

或作为一个集合初始化的一部分:

 新的List< INT> {1,2,3} 



或在一个变量声明:



  INT [] X = {1,2,3}; 

不可以合法使用数组初始化语法在其他任何情况下在其中表达的预期。例如:

  INT []×; 
X = {1,2,3};



是不合法的。



这只是C#语言的一个偏僻角落里的情况下。有没有更深层次的意思你发现不一致。


From: http://msdn.microsoft.com/en-us/library/2s05feca.aspx

Notice that you cannot omit the new operator from the elements initialization because there is no default initialization for the elements:

int[][] jaggedArray3 = 
{
    new int[] {1,3,5,7,9},
    new int[] {0,2,4,6},
    new int[] {11,22}
};

What does it mean?

Why is it ok to omit new in:

int[]    arrSimp = { 1, 2, 3 };
int[,]   arrMult = { { 1, 1 }, { 2, 2 }, { 3, 3 } };

but not possible in:

int[][,] arrJagg = {new int[,] { { 1, 1} }, new int[,] { { 2, 2 } }, new int[,] { { 3, 3 } } };

解决方案

First off, what a coincidence, an aspect of your question is the subject of my blog today:

http://ericlippert.com/2013/01/24/five-dollar-words-for-programmers-elision/

You've discovered a small "wart" in the way C# classifies expressions. As it turns out, the array initializer syntax {1, 2, 3} is not an expression. Rather, it is a syntactic unit that can only be used as part of another expression:

new[] { 1, 2, 3 }
new int[] { 1, 2, 3 }
new int[3] { 1, 2, 3 }
new int[,] { { 1, 2, 3 } }
... and so on

or as part of a collection initializer:

new List<int> { 1, 2, 3 }

or in a variable declaration:

int[] x = { 1, 2, 3 };

It is not legal to use the array initializer syntax in any other context in which an expression is expected. For example:

int[] x;
x = { 1, 2, 3 }; 

is not legal.

It's just an odd corner case of the C# language. There's no deeper meaning to the inconsistency you've discovered.

这篇关于省略C#转自铁血数组初始化新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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