【发布时间】: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# 中执行此操作。有什么建议吗?
【问题讨论】:
-
当您不想使用该对象时,为什么要实例化列表?