【问题标题】:List that I pass to function changes there c#我传递给函数更改的列表c#
【发布时间】:2017-12-26 13:51:41
【问题描述】:

这个函数有问题:

 static List<int> transposition(List<List<int>> main_list, int ammount)
    {
        List<int> return_list = new List<int>();
        List<int> b = new List<int>();
        List<List<int>> new_list = new List<List<int>>();
        new_list = main_list;
        int i = 0;
        int j = 0;
        int x = 0;
        int key = 0;
        Random rnd = new Random();
        foreach (List<int> subList in new_list)
        {
            x = subList[2];
        }
        while (i < ammount)
        {
            i++;
            key = rnd.Next(0, x + 1);
            while (j < new_list.Count)
            {
                if (key >= new_list[j][1] && key <= new_list[j][2])
                {
                    List<int> one_element = new List<int>();
                    one_element.Add(new_list[j][0]);
                    one_element.Add(new_list[j][1]);
                    one_element.Add(new_list[j][2]);
                    one_element.Add(new_list[j][3]);
                    if (j != 0)
                    {
                        b = new_list[j - 1];
                        new_list[j - 1] = one_element;
                        new_list[j] = b;
                    }
                }
                j++;
            }
        }
        foreach (List<int> element in new_list)
        {
            return_list.Add(element[3]);
        }
        return return_list;
    }

如您所见,我将“main_list”传递给该函数,问题是该列表在函数中发生了变化。我在 Python 中遇到了同样的问题,我通过添加 [:] 解决了这个问题,就像这个 'new_list = main_list[:]'。但我还没有找到如何在 c# 中执行此操作。有什么建议吗?

【问题讨论】:

标签: c# list function


【解决方案1】:

而不是

List<List<int>> new_list = new List<List<int>>();
new_list = main_list;

List<List<int>> new_list = new List<List<int>>(main_list);

这将创建一个从 main_list 获取其内容的新列表。 您创建了 main_list 的独立副本。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-24
    • 1970-01-01
    • 2020-06-03
    • 2016-03-11
    • 1970-01-01
    • 2017-08-12
    • 2012-03-07
    相关资源
    最近更新 更多