初始化C#阵列的新主场迎战与文本初始化 [英] Initializing c# array with new vs. initializing with literal

查看:160
本文介绍了初始化C#阵列的新主场迎战与文本初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简单的简短的问题
到底是什么

Simple Short Question What exactly is the difference between

int[] intarray = new int[2]{1,2};

int[] intarray2 = {4,5,6};



像什么是新做什么呢?
和你真的需要它吗?

Like what does the "new" do exactly? and do you really need it?

即时猜测它只是分配内存.....什么?对不起即时通讯完全新的C#和遇到我去学它的问题。

Im guessing it just allocates memory.....or something? Sorry im completely new to C# and have questions as I go about learning it.

推荐答案

第二个是的数组初始化语法。这只是语法糖。这两个初始化新的数组实例各自的价值,首先是更明确的(你重复,这是在右手侧的两个元素的整数数组,它是从什么如下所以编译器能够推断出这些信息很明显)。

The second is array initializer syntax. It's just syntactic sugar. Both initialize new array instances with their respective values, the first being more explicit (you repeat that it is an integer array of two elements on the right hand side which is pretty obvious from what follows so the compiler is capable of inferring this information).

所以下面的是等价的:

int[] array = new int[2] { 1, 2 };

int[] array = { 1, 2 };

var array = new[] { 1, 2 };

在所有的情况下,我们正在初始化两个整数的数组。我个人比较喜欢最后的语法。

In all cases we are initializing an array of two integers. Personally I prefer the last syntax.

这篇关于初始化C#阵列的新主场迎战与文本初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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