C# 标志问题

标签 c# .net asp.net variables enums

我有一个枚举(标志)

[Flags]
public enum DisplayMode
{
    None,
    Dim,
    Inverted,
    Parse,
    Italics,
    Bold
}

我想将两个标志分配给一个变量,如下所示:

var displayFlags = DisplayMode.Parse | DisplayMode.Inverted;

但是,当我调试并在分配后立即将鼠标悬停在该变量上时,它说 displayFlags is DisplayMode.Dim | DisplayMode.Inverted.

我缺少/不理解什么?

最佳答案

您错过了为标志分配合理的值,例如:

[Flags]
public enum DisplayMode
{
    None = 0,
    Dim = 1,
    Inverted = 2,
    Parse = 4,
    Italics = 8,
    Bold = 16
}

这样每个值在数字表示中都有一个单独的位。

如果您不相信自己将值加倍的能力,可以使用位移:

[Flags]
public enum DisplayMode
{
    None = 0,
    Dim =      1 << 0,
    Inverted = 1 << 1,
    Parse =    1 << 2,
    Italics =  1 << 3,
    Bold =     1 << 4
}

来自 FlagsAttribute 的文档:

Guidelines for FlagsAttribute and Enum

  • Use the FlagsAttribute custom attribute for an enumeration only if a bitwise operation (AND, OR, EXCLUSIVE OR) is to be performed on a numeric value.

  • Define enumeration constants in powers of two, that is, 1, 2, 4, 8, and so on. This means the individual flags in combined enumeration constants do not overlap.

...

关于C# 标志问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7534580/

相关文章:

c# - ListView 的检查包含特定数字

c# - 使用其他语音时的文本到语音 SAPI5 AccessViolationException

c# - 是否有没有唯一键的 Dictionary<Key,Value>?

ASP.NET 4.6 不响应 HTTP2( azure 网站)

asp.net - HTTP POST - 我卡住了

c# - Silverlight 与网络浏览器应用程序 (.xbab)?

c# - 使用自定义方法构造 AndAlso/OrElse LINQ 表达式

.net - 从网络共享运行 "partially trusted".NET 程序集

c# - IIS 我的网站文件夹已删除

c# - Web 服务 API 设计 - 输入验证和错误响应?