Color.GetPixel().equals(Color.Blue) 的结果是假的

Result of Color.GetPixel().equals(Color.Blue) comes out false

Color c1 = image.GetPixel (7, 400);
Color c2 = Color.Blue;
Console.WriteLine (image.GetPixel (7, 400));
Console.WriteLine (Color.Blue);
Console.WriteLine (c1.Equals(c2));

控制台输出:

Color [A=255, R=0, G=0, B=255]
Color [Blue]
False

我是 C# 的新手,我不知道为什么会返回 false。谁能告诉我为什么这不起作用?

我正在尝试在这种情况下使用它。

for (int i = 0; i < image.Height; i++)  //loop through rows
            {
            for (int j = 0; j < image.Width; j++) //loop through columns
            {
                //Console.WriteLine ("i = " + i);
                //Console.WriteLine ("j = " + j);
                if ((image.GetPixel (i, j)) == Color.Blue) 
                {
                    return new Tuple<int, int>(i,j);
                }

                if (i == image.Height-1 && j == image.Width-1) 
                {
                    Console.WriteLine ("Image provided does not have a starting point. \n" +
                                                 "Starting points should be marked by Blue.");
                    Environment.Exit (0);
                }
            }
        }

正如您已经注意到的,以下示例将 return 错误:

Bitmap bmp = new Bitmap(1, 1);
bmp.SetPixel(0, 0, Color.Blue);
Color c1 = bmp.GetPixel(0, 0);
Console.WriteLine("GetPixel:" + c1);
Console.WriteLine("Color:" + Color.Blue);
Console.WriteLine("Equal?:" + c1.Equals(Color.Blue));

Console.ReadLine();

原因有点难理解:

如果你查看Bitmap的源代码-Class,你会发现

public Color GetPixel(int x, int y) { 
   //lot of other code     
   return Color.FromArgb(color); 
 } 

http://reflector.webtropy.com/default.aspx/DotNET/DotNET/8@0/untmp/whidbey/REDBITS/ndp/fx/src/CommonUI/System/Drawing/Bitmap@cs/1/Bitmap@cs

Color.Equals() 的文档说:

To compare colors based solely on their ARGB values, you should use the ToArgb method. This is because the Equals and Equality members determine equivalency using more than just the ARGB value of the colors. For example, Black and FromArgb(0,0,0) are not considered equal, since Black is a named color and FromArgb(0,0,0) is not.

https://msdn.microsoft.com/en-us/library/e03x8ct2(v=vs.110).aspx

因此,returned 颜色不等于 Color.Blue - 即使就 ARGB 值而言它是 Color.Blue

要绕过这个,使用:

Console.WriteLine("Equal?:" + c1.ToArgb().Equals(Color.Blue.ToArgb()));

作为示例的最后一行。