gpt4 book ai didi

c# - 枚举的意外行为

转载 作者:太空宇宙 更新时间:2023-11-03 18:20:54 31 4
gpt4 key购买 nike

我使用 System.Drawing.RotateFlipType 实现了一个方法,并且在比较值时出现了奇怪的行为。

System.Drawing.RotateFlipType item1 = System.Drawing.RotateFlipType.RotateNoneFlipNone;
System.Drawing.RotateFlipType item2 = System.Drawing.RotateFlipType.Rotate180FlipXY;
Console.WriteLine(item1 == item2); //true

这怎么可能是真的?

最佳答案

作为canton7a comment 中指出,

If you think about it, it makes sense. "Specifies a 180-degree clockwise rotation followed by a horizontal and vertical flip." Do that transformation in your head, and you end up back where you started.

因此,RotateFlipTypeRotateNoneFlipNoneRotate180FlipXY 都具有相同的值(0) (API source)。

这在 reference source 中很明显(删除了 XML 注释):

public enum RotateFlipType
{
RotateNoneFlipNone = 0,
Rotate90FlipNone = 1,
Rotate180FlipNone = 2,
Rotate270FlipNone = 3,
RotateNoneFlipX = 4,
Rotate90FlipX = 5,
Rotate180FlipX = 6,
Rotate270FlipX = 7,
RotateNoneFlipY = Rotate180FlipX,
Rotate90FlipY = Rotate270FlipX,
Rotate180FlipY = RotateNoneFlipX,
Rotate270FlipY = Rotate90FlipX,
RotateNoneFlipXY = Rotate180FlipNone,
Rotate90FlipXY = Rotate270FlipNone,
Rotate180FlipXY = RotateNoneFlipNone,
Rotate270FlipXY = Rotate90FlipNone
}

拥有重复项没有坏处,所以我认为枚举的使用者更容易对同一事物拥有多个定义。

事实上,没有理由不能为枚举值提供重复的数值 - 实际上是 C# 语言规范 says :

Multiple enum members may share the same associated value. The example

enum Color 
{
Red,
Green,
Blue,
Max = Blue
}

shows an enum in which two enum members—Blue and Max—have the same associated value.

关于c# - 枚举的意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54749958/

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