【问题标题】:C#: ArrayList.Clear() clears the wrong arrayC#:ArrayList.Clear() 清除错误的数组
【发布时间】: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 数组。
  • 您的查询已由答案部分的作者解决。祝你好运。

标签: c# arrays arraylist


【解决方案1】:

数组变量是引用类型。当您调用 best=align 时,您并没有复制 align 的内容到 array,而是使它们指向同一个地方,即它们引用同一个内存位置。

试试best=align.Clone()

【讨论】:

  • 感谢您的回答!我尝试做 best=align.Clone(),但我得到了无法将 'object' 转换为 'Convert.Collections.ArrayList' 的东西。
  • 效果最好 = (ArrayList)align.Clone() 非常感谢
  • 很高兴能帮上忙!
【解决方案2】:

由于 align 是临时的,因此可以在调用 Score 之前重新创建它,并在需要时分配给 best:

public string AntColony()
{
    ArrayList best = null;

    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)

      ArrayList align = new ArrayList();
      score = Score(align);
      UpdatePhero(tao, path, score);

      if (score > score_before)
      {
         score_before = score;
         best = align;
      }
    }

    if (best != null)
    {
        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;
    }

    // TODO: Report failure here

    return null;
}

【讨论】:

  • 感谢您的回答!不幸的是,我需要在循环之前对齐数组来做其他事情!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多