列出 returns 不包含的内容

List returns what it does not contain too

我有一张图片,我在下面给出的列表中添加了一些像素。

 List<Color> ycolo = new List<Color>();
 for (int p = 5; p < FilteredImage.Width; p++) { 
      for (int k = 5; k < FilteredImage.Height ;k++)
      {
          ycolo.Add(FilteredImage.GetPixel(p, k));

          if (k==10) { break; }
      }
    if (p== 20) { break; }
}


if (!ycolo.Contains(FilteredImage.GetPixel(21,11)))
{
    MessageBox.Show("Im here");
}
else
{ MessageBox.Show("Im not here"); }

它 returns true(Im here),尽管它不包含 21,11 位置的像素 什么是错的 here.Im 在 Visual Studio c# 中工作。 怎么做才能让它发挥作用?

检查你的 if 语句。

if (!ycolo.Contains(FilteredImage.GetPixel(21,11)))
{
   MessageBox.Show("Im here");
}

您正在使用 ! 运算符,因此语句 ycolo.Contains(FilteredImage.GetPixel(21,11)) 将 return false 但 !运算符将使整个语句 true 并将打印 "Im here" 消息。

您混淆了像素的位置和颜色。 方法 FilteredImage.GetPixel(21,11) returns 像素的颜色。

要测试某个位置的像素是否已添加到列表中,请使用此代码:

List<System.Drawing.Point> ycolo = new List<System.Drawing.Point>();

for (int p = 5; p < FilteredImage.Width; p++)
{
    for (int k = 5; k < FilteredImage.Height; k++)
    {
        ycolo.Add(new System.Drawing.Point(p, k));

        if (k == 10) { break; }
    }
    if (p == 20) { break; }
}

if (ycolo.Contains(new System.Drawing.Point(21, 11)))
{
    MessageBox.Show("Im here");
}
else
{
    MessageBox.Show("Im not here");
}

作为进一步的改进,由于 2 点,我建议进行一些重构:

  • 您在两个不同的地方划分了 for 上限,例如您写的 FilteredImage.Widthif (p == 5) 的宽度。身高也一样。最好将 "upper limit" 这样的概念包含在一个地方,除非您的算法非常明确并且需要这种分离。
  • "p" 和 "k" 不是您的变量的重要名称,因为您的上下文处理宽度和高度,因此请改用 "w" 和 "h",或 "x" 和 "y"(自动被视为笛卡尔坐标)。

所以,这就是我编写代码的方式:

for (int w = 5; w < Math.Min(FilteredImage.Width, 20); w++)
{
    for (int h = 5; h < Math.Min(FilteredImage.Height, 10); h++)
    {
        ycolo.Add(new Point(w, h));
    }
}