[英]What is the reason for marking an enum with the [Flags] attribute?
我們最近將一個舊的C#應用程序從Visual Studio 2003移植到Visual Studio 2010。
在搜索代碼中要清理的東西時,我在上面運行了Resharper,它告訴我(很多次),“枚舉上的按位操作沒有標記[Flags]屬性”
例如,這里有一些代碼,它用該消息“標記”(沒有雙關語):
~DuckbillConverter()
{
//stop running thread
if((this.Status & ConvertStatus.Running) == ConvertStatus.Running)
this.Stop();
}
我假設這段代碼按原樣運行; 那么,如果R#建議用[Flags]屬性裝飾ConvertStatus.Running會有什么好處(或者更重要的是,任何可能的副作用)?
回答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不建議ConvertStatus.Running
接收屬性,但是整個ConvertStatus
枚舉。
從MSDN , FlagsAttribute
描述為:
表示可以將枚舉視為位字段; 也就是說,一組標志。
由於您對未指示實際可用作位字段的枚舉使用按位運算,因此R#警告您代碼可能在運行時具有意外影響。 使用[Flags]
屬性本身並不能保證枚舉的實現實際上與位字段的預期值一致,但它確實創建了外部世界應該期望的合同。
它告訴客戶端枚舉它確實是Flags。 此外,您可以看到微軟的例子 ,它修改了ToString()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.