如何在运行时分配数组值 [英] How to assign array values at run time

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

问题描述

考虑我有一个数组,

int[] i = {1,2,3,4,5};

在这里,我已经为其分配了值.但是在我的问题中,我仅在运行时获得这些值.如何将它们分配给数组.

Here I have assigned values for it. But in my problem I get these values only at runtime. How can I assign them to an array.

例如:

我从用户那里获取了数组的最大大小,并获得了它们的值,现在我该如何将它们分配给数组int [].

I get the max size of array from user and the values to them now how do I assign them to the array int [].

还是我可以使用其他任何数据类型(例如ArrayList等),都可以将其强制转换为Int []?

Or can I use anyother data types like ArrayList etc which I can cast to Int[] at the end?

推荐答案

最简单的方法是使用 List< T> :

List<int> list = new List<int>();
list.Add(1);
list.Add(2);
list.Add(3);
list.Add(4);
list.Add(5);
int[] arr = list.ToArray();

否则,您需要分配一个适当大小的数组,并通过索引器进行设置.

Otherwise, you need to allocate an array of suitable size, and set via the indexer.

int[] arr = new int[5];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;
arr[4] = 5;

如果您无法预测数组的大小,则第二种方法没有用,因为每次添加项目时重新分配数组都非常昂贵; List< T> 使用加倍策略来最大程度地减少所需的重新分配.

This second approach is not useful if you can't predict the size of the array, as it is expensive to reallocate the array every time you add an item; a List<T> uses a doubling strategy to minimize the reallocations required.

这篇关于如何在运行时分配数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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