[英]What is the reason for marking an enum with the [Flags] attribute?
We recently ported an old C# app from Visual Studio 2003 to Visual Studio 2010. 我们最近将一个旧的C#应用程序从Visual Studio 2003移植到Visual Studio 2010。
In searching for things to clean up in the code, I ran Resharper on it, and it tells me (oodles of times), "Bitwise operation on enum which is not marked by [Flags] attribute" 在搜索代码中要清理的东西时,我在上面运行了Resharper,它告诉我(很多次),“枚举上的按位操作没有标记[Flags]属性”
eg, here is a bit of code that it "flags" (no pun intended) with that message: 例如,这里有一些代码,它用该消息“标记”(没有双关语):
~DuckbillConverter()
{
//stop running thread
if((this.Status & ConvertStatus.Running) == ConvertStatus.Running)
this.Stop();
}
I assume that this code is working as is; 我假设这段代码按原样运行; so what would be the benefit (or, even more importantly, any possible side effects) of decorating ConvertStatus.Running with the [Flags] attribute, as R# recommends? 那么,如果R#建议用[Flags]属性装饰ConvertStatus.Running会有什么好处(或者更重要的是,任何可能的副作用)?
Answer to Jon Skeet: 回答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
}
Resharper isn't recommending that ConvertStatus.Running
receive an attribute, but the entire ConvertStatus
enum. Resharper不建议ConvertStatus.Running
接收属性,但是整个ConvertStatus
枚举。
From MSDN , FlagsAttribute
is described as: 从MSDN , FlagsAttribute
描述为:
Indicates that an enumeration can be treated as a bit field; 表示可以将枚举视为位字段; that is, a set of flags. 也就是说,一组标志。
Since you are using bitwise operations on an enum that isn't indicated to actually be usable as a bit field, R# is warning you that your code may have unintended effects at run time. 由于您对未指示实际可用作位字段的枚举使用按位运算,因此R#警告您代码可能在运行时具有意外影响。 Using the [Flags]
attribute itself doesn't guarantee that the implementation of the enum is actually consistent with the values expected for a bit field, but it does create a contract that the outside world should expect it to be. 使用[Flags]
属性本身并不能保证枚举的实现实际上与位字段的预期值一致,但它确实创建了外部世界应该期望的合同。
It tells the client of the enum that it is indeed Flags. 它告诉客户端枚举它确实是Flags。 Also you can see Microsoft's example in how it modifies ToString()
. 此外,您可以看到微软的例子 ,它修改了ToString()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.