我不时会看到如下的枚举:
[Flags]
public enum Options
{
None = 0,
Option1 = 1,
Option2 = 2,
Option3 = 4,
Option4 = 8
}
Run Code Online (Sandbox Code Playgroud)
我不明白[Flags]-attribute 到底是做什么的.
任何人都可以发布一个很好的解释或示例?
我正在尝试使用Interlocked.CompareExchange这个枚举:
public enum State {
Idle,
Running,
//...
}
Run Code Online (Sandbox Code Playgroud)
以下代码无法编译,但这就是我想要做的:
if (Interlocked.CompareExchange(ref state, State.Running, State.Idle) != State.Idle) {
throw new InvalidOperationException("Unable to run - not idle");
}
Run Code Online (Sandbox Code Playgroud)
当然我可以使用int而不是枚举并使用属性:
private int state = (int)State.Idle;
public State { get { return (State)state; } }
Run Code Online (Sandbox Code Playgroud)
然后将枚举转换为int:
if (Interlocked.CompareExchange(ref state, (int)State.Running, (int)State.Idle) != (int)State.Idle) {
throw new InvalidOperationException("Unable to run - not idle");
}
Run Code Online (Sandbox Code Playgroud)
但有没有更好的方法来做到这一点?
我如何可以比较System.Enum一个enum没有拳击?例如,如何在不装箱的情况下使下面的代码工作enum?
enum Color
{
Red,
Green,
Blue
}
...
System.Enum myEnum = GetEnum(); // Returns a System.Enum.
// May be a Color, may be some other enum type.
...
if (myEnum == Color.Red) // ERROR!
{
DoSomething();
}
Run Code Online (Sandbox Code Playgroud)
具体而言,此处的目的不是比较基础值.在这种情况下,基础值并不重要.相反,如果两个枚举具有相同的基础值,则如果它们是两种不同的枚举,则不应将它们视为相等:
enum Fruit
{
Apple = 0,
Banana = 1,
Orange = 2
}
enum Vegetable
{
Tomato = 0,
Carrot = 1,
Celery = 2
}
myEnum = Vegetable.Tomato;
if (myEnum != Fruit.Apple) // ERROR! …Run Code Online (Sandbox Code Playgroud) 最近工作的开发人员开始在枚举通常适合的地方使用类模式而不是枚举.相反,他使用类似于下面的东西:
internal class Suit
{
public static readonly Suit Hearts = new Suit();
public static readonly Suit Diamonds = new Suit();
public static readonly Suit Spades = new Suit();
public static readonly Suit Clubs = new Suit();
public static readonly Suit Joker = new Suit();
private static Suit()
{
}
public static bool IsMatch(Suit lhs, Suit rhs)
{
return lhs.Equals(rhs) || (lhs.Equals(Joker) || rhs.Equals(Joker));
}
}
Run Code Online (Sandbox Code Playgroud)
他的推理是它无形地看起来像枚举,但允许他包含与枚举有关的方法(如上面的IsMatch),它包含在枚举本身中.
他称这是一个Enumeration课程,但这不是我以前见过的.我想知道优点和缺点是什么以及我可以在哪里找到更多信息?
谢谢
编辑:他描述的另一个优点是能够为枚举添加特定的ToString()实现.