使用[Flags]属性标记枚举的原因是什么?

时间:2013-09-23 16:27:13

标签: c# enums resharper bit-manipulation

我们最近将一个旧的C#应用​​程序从Visual Studio 2003移植到Visual Studio 2010。

在代码中搜索要清理的东西时,我在上面运行了Resharper,它告诉我(很多次),“枚举上的按位操作没有标记[Flags]属性”

例如,这里有一些代码,它用这条消息“标记”(没有双关语):

~DuckbillConverter()
{
    //stop running thread
    if((this.Status & ConvertStatus.Running) == ConvertStatus.Running)
        this.Stop();
}

我认为这段代码按原样运行;那么使用[Flags]属性装饰ConvertStatus.Running会有什么好处(或者更重要的是,任何可能的副作用),如R#推荐的那样?

更新

对Jon Skeet的回答:

public enum ConvertStatus
{
    /// <summary>
    /// The thread is not running, there are no manual conversions or purges and no errors have occurred.
    /// </summary>
    Stopped = 0x0,
    /// <summary>
    /// The thread is running and will automatically convert all sites for both file types.
    /// </summary>
    Running = 0x1,
    /// <summary>
    /// A data conversion is currently taking place.
    /// </summary>
    Converting = 0x2,
    /// <summary>
    /// A data purge is currently taking place.
    /// </summary>
    Purging = 0x4,
    /// <summary>
    /// An error has occurred.  Use the LastError property to view the error message.
    /// </summary>
    Error = 0x8
}

2 个答案:

答案 0 :(得分:8)

Resharper不建议ConvertStatus.Running收到属性,而是整个ConvertStatus枚举。

MSDN开始,FlagsAttribute被描述为:

  

表示可以将枚举视为位字段;也就是说,一组标志。

由于您在枚举上使用按位操作未指示实际上可用作位字段,因此R#警告您代码可能在运行时具有意外影响。使用[Flags]属性本身并不能保证枚举的实现实际上与位字段的预期值一致,但它确实创建外部世界应该期望的契约它是。

答案 1 :(得分:1)

它告诉客户端枚举它确实是Flags。另外,您可以看到Microsoft's example如何修改ToString()