【发布时间】:2016-03-29 18:57:25
【问题描述】:
我在 C# 中使用 ArrayList 来做一些事情。 我有 2 个 ArrayList(align 和 best),并且在特定时间,我在“for”例程中设置了 best=align。
问题是,在循环结束时,我执行了 align.Clear,但此时,数组“best”也被清除了。在循环之后,当我必须使用数组“最佳”时,我遇到了麻烦,因为它被清除了,我尝试访问它的索引。
有什么问题?
这是我的一段代码:
public string AntColony()
{
ArrayList align = new ArrayList();
ArrayList best = new ArrayList();
for(int z=0;z<n_ants;z++)
{
//do the things i have to do
//full the array "align" with something (this will have two "adds", so, this array is a 2 lines array)
score = Score(align);
UpdatePhero(tao, path, score);
if (score > score_before)
{
score_before = score;
best = align;
}
align.Clear(); //clear the array align
}
string s = best[0].ToString() + "\r\n\r\n" + best[1].ToString() + "\r\n\r\n Number of matches: " + n_matches + "\r\n\r\n Score: " + score;
return s;
}
谢谢!
【问题讨论】:
-
您将
best引用指向align。 C# 是基于引用的! -
感谢您的回答。我能做些什么来解决这个问题?我的意思是,什么策略?无论如何,我必须让 best=align 最后清空 align 数组。
-
您的查询已由答案部分的作者解决。祝你好运。