Some basic definitions:
按位或运算符(|)是一种位运算符,用来对两个二进制数进行操作。对于每个位上的1,如果至少有一个二进制数中的对应位为1,则结果为1;否则,结果为0。
按位与运算符(&)是一种位运算符,用来对两个二进制数进行操作。对于每个位上的1,如果两个二进制数中的对应位为1,则结果为1;否则,结果为0。
Let’s look at the code first:
[Flags]
public enum Seasons
{
None = 0,
Summer = 1,
Autumn = 2,
Winter = 4,
Spring = 8,
All = Summer | Autumn | Winter | Spring
}
//枚举
var spring = Seasons.Spring;
var startingOnEquinox = Seasons.Spring | Seasons.Autumn;
var theYear = Seasons.All;
if (spring.HasFlag(Seasons.Spring)) Console.WriteLine("春天来了");
if (theYear.HasFlag(Seasons.Winter)) Console.WriteLine("冬天来了");
if (startingOnEquinox.HasFlag(Seasons.Autumn)) Console.WriteLine("秋天来了");
Console.WriteLine("C#牛皮。C#接单QQ群 452760896");
This is an enumeration representing seasons, mainly looking at the last ALL which represents the enumeration of all seasons above.
Many people sometimes don't know why.
Today I will explain in detail:
why ALL contains all the above seasonal options, we calculate it in binary.
当使用位运算符按位或(|)将枚举常数的值进行操作时,它的原理是将各个二进制位对应的数值进行合并。对于每个位上的1,如果至少有一个枚举常数中对应位为1,则结果为1;否则,结果为0。
假设一个枚举类型中有4个枚举常数如下: Summer: 0001 Autumn: 0010 Winter: 0100 Spring: 1000
按位或操作的结果为: 0001 | 0010 | 0100 | 1000 = 1111
得到了二进制数1111,转换为十进制数即为15。所以,All枚举常数的值为15,表示All代表所有的季节,包括Summer,Autumn,Winter和Spring。
这种按位或运算的机制可以将多个二进制数的对应位合并起来,以获得一个包含多个选项的组合值。在使用枚举时,可以通过进行按位与运算(&)来判断一个特定的选项是否包含在枚举常数中。如果按位与运算的结果不为0,则表示包含在其中;否则,表示不包含。
The calculated result is ALL
and 15
the corresponding binary is: 1111
And because HasFlag
the bottom layer of this method is actually 按位与(&)
calculating, it determines whether the current value is not and returns 0
if it is. For example, this code: the binary represented is the binary represented by the bitwise AND of them and returned The value is that of itself. so return0
false
if (theYear.HasFlag(Seasons.Winter)) Console.WriteLine("冬天来了");
theYear
1111
Seasons.Winter
0100
0100
Seasons.Winter
True
这里强调下,如果要用按位与或者或请一定要让有效值是2的次方。因为是二进制嘛。
[Flags] 是一个特性(Attribute),用于标记枚举类型支持按位组合的选项。
当在枚举类型上应用 [Flags] 特性时,它告诉编译器该枚举类型的值可以进行按位组合。这样一来,可以使用按位或操作符(|)将多个枚举常数的值组合成一个新的枚举值。
在上面的示例中,使用 [Flags] 特性修饰了 Seasons 枚举类型。这表示枚举类型 Seasons 的值可以进行按位组合。
当使用 [Flags] 特性时,建议为枚举类型指定具有特殊含义的值,如 None 和 All,以及按位组合的其它枚举常数。
operation result: