【问题标题】:Defining an array list in c# unity.在 c# unity 中定义数组列表。
【发布时间】:2017-07-27 12:02:25
【问题描述】:

我正在尝试创建一个整数值的数组列表并运行一些基本的数学运算,如下所示。

int dice1 = 4;
int dice2 = 3;
int dice3 = 6;
int dice4 = 4;
int dice 5 = 5;

ArrayList numbers = new  ArrayList();
        numbers[4] = dice5;
        numbers[3] = dice4;
        numbers[2] = dice3;
        numbers[1] = dice2;
        numbers[0] = dice1;

numbers[3] = numbers[3] * numbers[2];

但是,计算机不允许我这样做并产生错误“运算符“*”不能应用于“对象”和“对象”类型的操作数”。我该如何解决?我认为我必须将数组列表定义为整数数组......但是我不太确定。请保持答案简单,因为我对 C# unity 还很陌生。

谢谢!

【问题讨论】:

    标签: c# arrays unity3d arraylist


    【解决方案1】:

    ArrayList 将所有内容存储为“对象”,基本上是 C# 中最基本的类型。你有几个选择。如果你想继续使用 ArrayList,那么你需要转换你正在乘法的东西,比如:

    numbers[3] = ((int)numbers[3]) * ((int)numbers[2])
    

    或者,您可以放弃 ArrayList 并使用更现代的 List 类型。您需要在顶部添加using System.Collections.Generic,然后您的代码将如下所示:

    int dice1 = 4;
    int dice2 = 3;
    int dice3 = 6;
    int dice4 = 4;
    int dice5 = 5;
    
    List<int> numbers = new List<int>(); //List contains ints only
        numbers[4] = dice5;
        numbers[3] = dice4;
        numbers[2] = dice3;
        numbers[1] = dice2;
        numbers[0] = dice1;
    
    numbers[3] = numbers[3] * numbers[2]; //Works as expected
    

    最后,如果您知道您的集合中只有一定数量的东西,您可以使用数组来代替。您的代码现在将是:

    int dice1 = 4;
    int dice2 = 3;
    int dice3 = 6;
    int dice4 = 4;
    int dice5 = 5;
    
    int[] numbers = new int[5]; //Creates an int array with 5 elements
    //Meaning you can only access numbers[0] to numbers[4] inclusive
        numbers[4] = dice5;
        numbers[3] = dice4;
        numbers[2] = dice3;
        numbers[1] = dice2;
        numbers[0] = dice1;
    
    numbers[3] = numbers[3] * numbers[2]; //Works as expected
    

    【讨论】:

    【解决方案2】:

    避免使用数组列表

    使用List&lt;int&gt;int[]

    然后包含的对象是类型而不是对象

    【讨论】:

      【解决方案3】:

      你可以在一行中完成:

      List<int> numbers = new List<int>{ 4, 3, 6, 4, 5 };
      

      【讨论】:

        【解决方案4】:

        您需要将对象解析为字符串,然后解析为 int 值,然后将其与 * 运算符一起使用。但是您首先必须使用空值初始化数组列表,然后分配数字值这样, 使用我为你做了明确更改的以下代码。

        int dice1 = 4;
            int dice2 = 3;
            int dice3 = 6;
            int dice4 = 4;
            int dice5 = 5;
            int capacity=5;
            ArrayList numbers = new ArrayList(capacity);
            for (int i = 0; i < capacity;i++ )
            {
                numbers.Add(null);
            }
            numbers[4] = dice5;
            numbers[3] = dice4;
            numbers[2] = dice3;
            numbers[1] = dice2;
            numbers[0] = dice1;
        
            numbers[3] = (int.Parse(numbers[3].ToString()) * int.Parse(numbers[2].ToString()));
            print(numbers[3]);
        

        【讨论】:

          猜你喜欢
          • 2018-02-15
          • 1970-01-01
          • 2012-04-08
          • 1970-01-01
          • 2021-12-20
          • 2017-06-04
          • 2015-02-11
          • 2014-04-10
          相关资源
          最近更新 更多