CA2217:不要以 FlagsAttribute 標記列舉
型別名稱 |
DoNotMarkEnumsWithFlags |
CheckId |
CA2217 |
分類 |
Microsoft.Usage |
中斷變更 |
不中斷 |
原因
從外部可見的列舉會以 FlagsAttribute 標記,並且有一個或多個不是二的次方,或組合列舉上其他定義值之次方的值。
規則描述
只有當列舉型別中定義的每個值都是二的次方或已定義值的組合時,列舉型別中才會有 FlagsAttribute 存在。
如何修正違規
若要修正此規則的違規情形,請從列舉型別中移除 FlagsAttribute。
隱藏警告的時機
請勿隱藏此規則的警告。
範例
下列範例會示範其中包含值 3 的 Color 列舉,這個列舉不是二的次方,也不是組合任何定義值的次方。Color 列舉不應該以 FlagsAttribute 標記。
Imports System
Namespace Samples
' Violates this rule
<FlagsAttribute()> _
Public Enum Color
None = 0
Red = 1
Orange = 3
Yellow = 4
End Enum
End Namespace
using System;
namespace Samples
{
// Violates this rule
[FlagsAttribute]
public enum Color
{
None = 0,
Red = 1,
Orange = 3,
Yellow = 4
}
}
using namespace System;
namespace Samples
{
// Violates this rule
[FlagsAttribute]
public enum class Color
{
None = 0,
Red = 1,
Orange = 3,
Yellow = 4
};
}
下列範例會示範符合以 System.FlagsAttribute 標記之需求的 Days 列舉。
Imports System
Namespace Samples
<FlagsAttribute()> _
Public Enum Days
None = 0
Monday = 1
Tuesday = 2
Wednesday = 4
Thursday = 8
Friday = 16
All = Monday Or Tuesday Or Wednesday Or Thursday Or Friday
End Enum
End Namespace
using System;
namespace Samples
{
[FlagsAttribute]
public enum Days
{
None = 0,
Monday = 1,
Tuesday = 2,
Wednesday = 4,
Thursday = 8,
Friday = 16,
All = Monday| Tuesday | Wednesday | Thursday | Friday
}
}
using namespace System;
namespace Samples
{
[FlagsAttribute]
public enum class Days
{
None = 0,
Monday = 1,
Tuesday = 2,
Wednesday = 4,
Thursday = 8,
Friday = 16,
All = Monday| Tuesday | Wednesday | Thursday | Friday
};
}
相關規則
CA1027:必須以 FlagsAttribute 標記列舉