C#中声明数组之间的区别

difference between declaring arrays in c# [duplicate]
2021-07-31
  •  译文(汉语)
  •  原文(英语)

在研究C#时,我有以下疑问.由于数组在C#中是引用类型,因此在声明时我认为它们一直分配在堆上.因此,当我们以以下方式声明数组时:

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

它们之间有什么区别吗?

我们可以int arr[100];像在C ++中那样声明数组吗?(无需初始化且不使用new关键字),然后在以后为它们赋值.

速聊1:
只要看看这个Eric Lippert的答案,就已经有人问过了
速聊2:
after this function returns you can still use arr2 你到底在说什么
速聊3:
我认为在C ++中是正确的,而不是在C#中
速聊4:
数组是引用类型,因此不能在堆栈上分配.
速聊5:
谢谢,我得到第一个问题的答案.我们可以声明int arr [100]; 在C#中像在C ++中一样?(或类似的语法)
解决过程1

其数组初始化语法

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

他们是一样的.在这种情况下...

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

因为您在必须匹配数量之后声明了size [3].

检查本教程http://msdn.microsoft.com/en-us/library/aa288453(v=vs.71).aspx

编辑:

int[] MyArray = new int[100];
            int[] MyOtherArray = MyArray;

这是您可以对第二个问题做的事情

While studying C#,I got the following doubt.Since arrays are reference types in C# when declared I think they are allocated on heap all the time.So when we declare array in following the ways:

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

Is there any difference between them?

And can we declare array int arr[100]; like in C++?(without initializing and without using new keyword)And then assign them value later.

Talk1:
Just look at this Eric Lippert answer, it have been asked before
Talk2:
after this function returns you can still use arr2 What the heck are you talking about?
Talk3:
that is true in C++ not in C# i think
Talk4:
An array is a reference type, so it cannot be allocated on the stack.
Talk5:
-LucPineault Thanks,I got the answer for the first question.can we declare int arr[100]; in C# like we do in C++?(or similar syntax)
Solutions1

Its the array initialization syntax

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

they are the same. In this case...

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

since you declared the size[3] after you must match the quantity.

check this tutorial http://msdn.microsoft.com/en-us/library/aa288453(v=vs.71).aspx

EDIT:

int[] MyArray = new int[100];
            int[] MyOtherArray = MyArray;

this is what you can do about your second question

转载于:https://stackoverflow.com/questions/17087950/difference-between-declaring-arrays-in-c-sharp

本人是.net程序员,因为英语不行,使用工具翻译,希望对有需要的人有所帮助
如果本文质量不好,还请谅解,毕竟这些操作还是比较费时的,英语较好的可以看原文

留言回复
我们只提供高质量资源,素材,源码,坚持 下了就能用 原则,让客户花了钱觉得值
上班时间 : 周一至周五9:00-17:30 期待您的加入