【问题标题】:How can I append values in a C# array? [duplicate]如何在 C# 数组中附加值? [复制]
【发布时间】:2017-10-13 17:41:02
【问题描述】:

我需要通过用户输入一次向我的数组添加一个整数值。

我不知道如何更清楚地问它,但我的目标是在 Main() 中定义一个整数数组,然后将其传递给 Interactive(),用户应该在其中输入 20 个不同的整数,程序应该将它们添加到数组中。

继续为每个对象定义新参数会很乏味(像这样):

int One = ArrayOne[0]
int Two = ArrayOne[1]
int Three = ArrayOne[2]

因为我要填充 20 个数组对象,所以肯定有更简单的方法吗?

有人可以帮忙吗?

这是我正在使用的代码:

    class Program
    {
        static void Main(string[] args)
        {
            int[] intArray = new int[20];
        }

        public static int[] Interactive(int[] args)
        {
            int[] ArrayOne = new int[20];

            Write("\n   Write an integer >>");
            ArrayOne[0] = Convert.ToInt32(ReadLine());

            foreach (int x in ArrayOne)
            {
                if (x != ArrayOne[0])
                    Write("\n   Write another integer");
                ArrayOne[x] = Convert.ToInt32(ReadLine());
                WriteLine("\n   {0}", ArrayOne[x]);
            }

            ReadLine();

            return ArrayOne;
        }

    }

【问题讨论】:

  • 请您的讲师检查链接的重复项,以阐明他们希望您复制粘贴哪个答案 - 将元素添加到预先分配的数组中,然后增加数组大小。

标签: c# arrays methods append parameter-passing


【解决方案1】:

尝试使用List。与数组不同,它们的大小可以动态更改。

using System.Collections.Generic;

public class Example
{
    public static void Main()
    {
        List<int> numbers = new List<int>();
        numbers.add(1);
        numbers.add(2);
    }

}

【讨论】:

  • 我最初有一个列表,但我的导师要求我使用数组。不过谢谢!
  • List 在“幕后”使用了一个数组。
【解决方案2】:

你在找这个吗?

 int[] intArray = Interactive(values here);

public static int[] Interactive(int[] args)
    {
     //TODO:
    }

【讨论】:

  • 嗯。我不知道这有多大帮助。我猜我已经弄清楚了那部分。我需要通过用户输入一次向我的数组添加一个 int 值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-11
  • 2012-08-07
  • 1970-01-01
相关资源
最近更新 更多