【问题标题】:How can I delete element from my list (Array)? [duplicate]如何从列表(数组)中删除元素? [复制]
【发布时间】:2022-08-11 01:19:40
【问题描述】:

因此,我复制了这个脚本,它从列表中随机获取一个值,然后将其写在控制台上,并且我想要这样做,如果选择了某个值而不是相同的值,那么该值将从列表中删除。但是我发现了被选中的值不是整数形式的问题。它设置为 var,我不知道如何更改或转换它。我的目标是找到一种方法将该 var 设置为 int,或者以某种方式使用 var state 从我的列表中删除它。我在这个问题上头疼了好几个小时,却无法解决。这是我的代码...在此先感谢。

List<int> list = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    List<T> GetRandomElements<T>(List<T> inputList, int count)
    {
        List<T> outputList = new List<T>();
        for (int i = 0; i < count; i++)
        {
            int index = Random.Range(0, inputList.Count);
            outputList.Add(inputList[index]);
        }
        return outputList;
    }

    void Update()
    {

        if (Input.GetMouseButtonDown(0))
        {
            var randomList = GetRandomElements(list, 1);

            Debug.Log(\"All elements =>  \" + string.Join(\", \", list));
            Debug.Log(\"Random elements => \" + string.Join(\", \", randomList));
            Debug.Log(\"*****************************\");

            RemoveElement(ref list, randomList);
        }
    }

    private void RemoveElement<T>(ref T[] arr, int index)
    {
        for (int i = index; i < arr.Length - 1; i++)
        {
            arr[i] = arr[i + 1];
        }

        Array.Resize(ref arr, arr.Length - 1);
    }

    标签: c# unity3d game-development


    【解决方案1】:

    var 是一个隐式类型的变量。它采用在编译时分配给它的任何数据类型。在这种情况下

    var randomList = GetRandomElements(list, 1);
    

    是整数列表,因为 GetRandomElements 接受整数列表作为参数并返回整数列表。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-12
      • 1970-01-01
      • 1970-01-01
      • 2015-09-14
      • 1970-01-01
      • 1970-01-01
      • 2016-12-03
      相关资源
      最近更新 更多