c#通过用户输入向数组添加值
本文关键字:数组 添加 输入 用户 | 更新日期: 2023-09-27 18:07:50
我想通过用户输入向数组中添加元素。我知道这可以很容易地完成使用列表,但我必须使用数组。
代码的问题是数组。长度总是1。我想让这个数组的大小等于它的元素总数,所以在声明数组时不应该设置数组的大小。
我认为,如果你添加一个元素到一个数组,它会复制之前的值+增加的值,并创建一个新的数组。
更新答案
public static void Add(int x){
if (Item == null) // First time need to initialize your variable
{
Item = new int[1];
}
else
{
Array.Resize<int>(ref Item, Item.Length + 1);
}
Item[Item.Length-1] = x; //fixed Item.Length -> Item.Length-1
}
使用List<int>
代替显式数组,它将动态地为您调整大小,并使用Add()方法在末尾添加元素。
我没有在vs中测试:
namespace ConsoleApplication1
{
class Program
{
static int[] Item; //Fixed int Item[] to int[] Item
static void Main(string[] args)
{
Add(3);
Add(4);
Add(6);
}
public static void Add(int x){
if (Item == null) // First time need to initialize your variable
{
Item = new int[1];
}
else
{
Array.Resize<int>(ref Item, Item.Length + 1);
}
Item[Item.Length-1] = x; //fixed Item.Length -> Item.Length-1
}
}
}
这将每次调整数组的大小,然后将最后一项设置为您要添加的内容。注意,这是非常低效的。
列表随着添加元素而增长。数组的大小是固定的。如果必须使用数组,最简单的方法是创建一个足够大的数组来容纳输入的元素。
private int[] _items = new int[100];
private int _count;
public void Add(int x)
{
_items[_count++] = x;
}
您还需要跟踪已经插入的元素的数量(我在这里使用_count
字段);
作为一个例子,您可以像这样枚举所有的项:
for (int i = 0; i < _count; i++) {
Console.WriteLine(_items[i]);
}
您可以像这样使项可公开访问:
public int[] Items { get { return _items; } }
public int Count { get { return _count; } }
如果您想要自动增加数组大小,当数组变得太小时,最好将实际大小增加一倍。这是速度和内存效率之间的一个很好的折衷(这就是列表的内部工作方式)。
private int[] _items = new int[8];
private int _count;
public void Add(int x)
{
if (_count == _items.Lengh) {
Array.Resize(ref _items, 2 * _items.Length);
}
_items[_count++] = x;
}
但是,记住这改变了数组引用。因此,不应该将此数组引用的永久副本存储在其他任何地方。