gpt4 book ai didi

.net - System.Drawing.Color 相等运算符不会将 0xffffffff 视为 Color.White

转载 作者:行者123 更新时间:2023-12-02 00:34:43 25 4
gpt4 key购买 nike

为什么它的计算结果为false

Color.FromArgb(255, 255, 255, 255) == Color.White

更新这是设计使然。

这是 Color 结构中反编译的 Equals 函数的副本:

public override bool Equals(object obj)
{
//probably failure to convert from C++ source,
//the following line should be invalid in C#, nevermind
if (obj is Color)
{
Color color = (Color) obj;
if (((this.value == color.value) &&
(this.state == color.state)) &&
(this.knownColor == color.knownColor))
{
return ((this.name == color.name) ||
(((this.name != null) && (color.name != null)) &&
this.name.Equals(this.name)));
}
}
return false;
}

我的问题是,为什么 MSFT 会让我以丑陋的方式与白人进行比较?!?!?

static bool AreEqual(Color a, Color b)
{
if (!a.Equals(b))
{
return
a.A == b.A &&
a.R == b.R &&
a.G == b.G &&
a.B == b.B;
}
return true;
}

另外,我不明白为什么 Color 中的 FromArgb 函数的 1-arg 重载采用 int,它应该能够获取一个uint (0xffffffff)

最佳答案

这只是how colors in .NET work :

This structure only does comparisons with other Color structures. To compare colors based solely on their ARGB values, you should do the following:

if ( color1.ToArgb() == color2.ToArgb()) ...

This is because the .Equals and == operators determine equivalency using more than just the ARGB value of the colors. For example, Color.Black and Color.FromArgb(0,0,0) are not considered equal since Color.Black is a named color and Color.FromArgb(0,0,0) is not.

编辑:其他答案。

My question is why on earth would MSFT have me comparing to white the ugly way?!?!?

如果您比较颜色的方式是想知道它们是否与 ARGB 分量的值完全相同,那么您应该在“丑陋”的方式。如果您以大多数 .NET 程序员使用 Color 结构的方式比较颜色,那么您只想知道某种颜色是 White 还是 RedChartreuse,“漂亮”的方式(使用 Equals 和 ==)简单、易于使用且可读性强。

此外,“丑陋”的方法不是您发布的方法,而是这样的:

if (color1.ToArgb() == color2.ToArgb()) ...

这其实并没有那么难看。

Also, another thing I don't get why the 1-arg constructor of Color takes an int, it should be able to take a uint (0xffffffff)

我想说它不应该不能能够接受uint,因为这会导致不可避免的困惑和颜色错误。编写一个方法来执行此操作很容易。

关于.net - System.Drawing.Color 相等运算符不会将 0xffffffff 视为 Color.White,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8146453/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com