c# 枚举定义前的[Flags]是什么意思?

2025-04-29 23:52:43
推荐回答(5个)
回答1:

指示可以将枚举作为位域(即一组标志)处理。

回答2:

class FlagsAttributeDemo
{
// Define an Enum without FlagsAttribute.
enum SingleHue : short
{
Black = 0,
Red = 1,
Green = 2,
Blue = 4
};

// Define an Enum with FlagsAttribute.
[FlagsAttribute]
enum MultiHue : short
{
Black = 0,
Red = 1,
Green = 2,
Blue = 4
};

static void Main( )
{
Console.WriteLine(
"This example of the FlagsAttribute attribute \n" +
"generates the following output." );
Console.WriteLine(
"\nAll possible combinations of values of an \n" +
"Enum without FlagsAttribute:\n" );

// Display all possible combinations of values.
for( int val = 0; val <= 8; val++ )
Console.WriteLine( "{0,3} - {1}",
val, ( (SingleHue)val ).ToString( ) );

Console.WriteLine(
"\nAll possible combinations of values of an \n" +
"Enum with FlagsAttribute:\n" );

// Display all possible combinations of values.
// Also display an invalid value.
for( int val = 0; val <= 8; val++ )
Console.WriteLine( "{0,3} - {1}",
val, ( (MultiHue)val ).ToString( ) );
}
}

/*
This example of the FlagsAttribute attribute
generates the following output.

All possible combinations of values of an
Enum without FlagsAttribute:

0 - Black
1 - Red
2 - Green
3 - 3
4 - Blue
5 - 5
6 - 6
7 - 7
8 - 8

All possible combinations of values of an
Enum with FlagsAttribute:

0 - Black
1 - Red
2 - Green
3 - Red | Green
4 - Blue
5 - Red | Blue
6 - Green | Blue
7 - Red | Green | Blue
8 - 8
*/

回答3:

这种用处很大,比如权限、执行状态等,都可以用一个int型保存到数据库中,C#中使用枚举可以处理这个问题。
[Flags]

public enum Permission
{
create = 1,
read = 2,
update = 4,
delete = 8,
}

在数据库中判断:
AND (@permission IS NULL OR @permission=0 OR permission &@permission =@permission)

回答4:

设置一个变量flag,是一个来表示判断的变量,当做标志

回答5:

到这看看
http://hi.baidu.com/cnfczn/blog/item/b2d093ee79feeb212cf5340a.html