动态数组大小扩展 [英] Dynamic Array Size Extension

查看:73
本文介绍了动态数组大小扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

数组可以像Matlab Simulink中那样自动扩展其大小吗?在Matlab Simulink中,数组不受限于声明的数组大小.您分配给relevent数组的元素越多,该数组会自动使其自身越大.

例如,说我声明一个数组:

Can an array extend its size automatically like in Matlab Simulink where you are not limited to a declared array size. The more elements you assign to the relevent array, the bigger the array automatically makes itself.

eg, say I declare an array:

double[,] Numbers = new double[10,4];



现在,在Simulink中说,我发现在运行时数组实际需要为[30,6],它将自动相应地调整其范围以适应分配给它的新元素.因此,设置数组大小是多余的,因为该数组可以根据需要有效地收缩和扩展.

C#是否具有此功能?如果不是,如何在运行时增加数组大小而无需声明[10000,10000]数组来容纳我可能需要的所有可能的元素?



now, say in Simulink I find that during runtime the array actualy needs to be [30,6], it would automatically adjust itseld accordingly to accomadate the new elements you assigned to it. Therefore, a set array size is redundant as the array can effectively shrink and expand as need be.

Does C# have this capablility? If not, how can I increase my array size during runtime without needing to declare an array of [10000,10000] to accomodate ALL possible elements I might need?

推荐答案

做类似的事情:


var newArray = new double [30,6];

Array.Copy(array,newArray,array.Length);

然后,您可以将其转换为扩展方法,以使您的代码更具美感:

公共静态类ExtensionMethods
{
公共静态T [,] Resize< T(此T [,]数组,整型size1,整型size2)
{
var newArray = new T [size1,size2];

Array.Copy(array,newArray,array.Length);

返回newArray;
}
}

并这样称呼:

array = array.Resize(30,6);
Do something like:


var newArray = new double[30,6];

Array.Copy(array, newArray, array.Length);

You could then turn this into an extension method to make your code more asthetically pleasing:

public static class ExtensionMethods
{
public static T[,] Resize<T>(this T[,] array, int size1, int size2)
{
var newArray = new T[size1, size2];

Array.Copy(array, newArray, array.Length);

return newArray;
}
}

and call it like so:

array = array.Resize(30, 6);


如果在c#控制台应用程序中,则可以向用户询问数组的大小.喜欢:

If it is in c# console application you can ask to the user for the size of array. Like:

Console.WriteLine("Enter the size of the array: ");
int size=Convert.ToInt32(Console.ReadLine());
int [] arr=new int[size];



而且,如果它在ASP.Net或Windows应用程序中,则可以每次增加一个数组的大小..



And if it is in ASP.Net or Windows Application then you can take a count to increase the size of your array every time..


您可以使用 ^ ]或列表列表.

除此之外,我怀疑您会发现 http://www.mathdotnet.com/ [
You could use a List[^] or a list of lists.

Apart from that, I suspect that you will find that http://www.mathdotnet.com/[^] provides more of the functionality you need.

Best regards
Espen Harlinn


这篇关于动态数组大小扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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