Flags 属性好像没有效果 [英] Flags attribute seems to have no effect

查看:32
本文介绍了Flags 属性好像没有效果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请看下面的代码:

Public Class Form1

    <Flags> _
    Public Enum Days
        Monday = 0
        Tuesday = 1
        Wednesday = 2
    End Enum

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
        Dim s As String = (Days.Monday Or Days.Tuesday).ToString()
    End Sub
End Class

s 的值变为:星期二.我希望它是:星期一,星期二,根据 Thomas Levesque 的回答:FlagsAttribute 有什么用?.

The value of s becomes: Tuesday. I would expect it to be: Monday,Tuesday as per Thomas Levesque's answer here: FlagsAttribute what for?.

我做错了什么?

更新 Jon Skeets 回答后,我试过了:

UPDATE After Jon Skeets answer I have tried this:

<Flags> _
    Public Enum Days
        None = 0
        Monday = 1
        Tuesday = 2
        Wednesday = 4
    End Enum

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
        Dim s As String = (Days.Monday And Days.Tuesday).ToString()
    End Sub

然而,s"现在等于NONE"?数字序列中是否有任何逻辑,即 0、1、2、4、8 等,或者我可以使用 0、1、2、3、4 等.

However, 's' now equals 'NONE'? Also is there any logic in the sequence of numbers i.e. 0,1,2,4,8 etc or could I use 0,1,2,3,4 etc.

推荐答案

我做错了什么?

您给 Monday 的值为 0,这意味着它在您执行按位或时无关紧要.

You're giving Monday a value of 0, which means it's irrelevant when you perform a bitwise-OR.

在基于 Flags 的枚举中唯一合理的语义值 0 是 None.

The only sensible semantic value of 0 in a Flags-based enum is None.

你应该:

<Flags> _
Public Enum Days
    None = 0
    Monday = 1
    Tuesday = 2
    Wednesday = 4
    Thursday = 8
    ...
End Enum

请注意,除了我包含的无"值之外,这与您提到的帖子中给出的值相同.价值观很重要!它们实际上是被存储的东西……这些名字只是对我们人类有用.

Note that aside from the "none" value I've included, that's the same as the values given in the post you referred to. The values are important! They're effectively what gets stored... the names are just useful for us as humans.

现在您已经更新了代码,您已将运算符从 Or 更改为 And,因此您正在执行 1 和 2 的按位 AND...这是0.要添加,您需要使用Or.

Now you've updated your code, you've changed the operator from Or to And, so you're performing a bitwise AND of 1 and 2... which is 0. To be additive, you need to use Or.

是的,数字序列是精确按位的,每次都翻倍:1、2、4、8、16、32 等.0 的无"值只是未设置位".我建议您阅读 FlagsAttribute 文档 小心.

And yes, the sequence of numbers is precisely bitwise, doubling each time: 1, 2, 4, 8, 16, 32 etc. The "none" value of 0 is just "no bits set". I suggest you read the FlagsAttribute documentation carefully.

这篇关于Flags 属性好像没有效果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆