如何在CSharp中调整数组大小 [英] How to resize an array in CSharp

查看:132
本文介绍了如何在CSharp中调整数组大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码如下:

I have code as follow:

Dim aRead() As String
      Dim  nCnt,i As Iteger  
      nCnt = 0
      For i=0 to 5               
         ReDim Preserve aRead(nCnt)                           
         aRead(nCnt) = i
      Next i
      nCnt = nCnt + 1



现在我想将其转换为C#,那么我该怎么办?
我尝试了以下方法,但没有尝试:



and now I want to convert it to C#, so How must I do?
I tried as below but not:

int i,nCnt = 0;
string[] aRead = null;
For(i=0;i<=5;i++){
Array.Resize(ref aRead, nCnt);
aRead[nCnt] = i;
nCnt = nCnt + 1;
}



你能帮我吗?



could you help me please.
thanks.

推荐答案

最接近的C#等效项是Array.Resize<T>,但即使那样,它也会创建一个新数组,并通过旧数组复制到新数组中.
如果您想要一个可以根据需要增长的类似数组的集合,请使用List<T>.那将是一种更.NET风格的处理方式.

从经典的VB迁移到.NET时,还不足以学习新的语法,还需要了解新的框架并尝试遵循推荐的.NET做法.
The closest C# equivalent is Array.Resize<T> but even that creates a new array and copies over the old array into the new array.

If you want an array-like collection that can grow as required, use List<T>. That would be a more .NET-ish way of doing things.

When moving from classic VB to .NET, it''s not enough to learn the new syntax, you also need to understand the new framework and try and follow recommended .NET practices.


Nishant提到的Array.Resize会做到这一点.但这是昂贵的操作,因为每个调用都会创建一个新数组.

另外,您可以提前从代码中知道超出数组大小的位置.因此,您无需在循环中调整其大小,只需定义一次即可完成.

As Nishant mentioned Array.Resize will do it. But it is expensive operation as each call will create a new array.

Alternatively, you know from your code above your array size ahead of time. So you don''t need to Resize it in the loop, rather have it defined once and you are done.

int i;
string[] aRead = new string[5];
for(i=0;i<=5;i++){
 aRead[i] = i;
}



替代方法2:如果您认为需要增加阵列,请使用 ArrayList [^ ]



Alternative 2: If you think you will need to grow your array then use ArrayList[^]

ArrayList myAL = new ArrayList();
for(i=0;i<=5;i++){
      myAL.Add(i);
}


例如,我使用从0到5的值,这里的问题是我无法在循环中升起数组.因为在第一次运行时调试它时,调整了大小但是第二个有bug.
我认为在C#中,不允许像在VB中那样循环使用数组.也许我必须计算时间循环,然后调整数组大小,这样就可以了.
I use for from 0 to 5 to for example and the problem in here is I can not riseze array in loop.Because when I debug it the first run it is resized ok but the second has bug.
I think that in C# it do not allow we risize array in loop as in VB. Maybe I must count the time loop and then resize my array and this way is ok.


这篇关于如何在CSharp中调整数组大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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