如何测试数字中是否包含枚举?
在vb6中,我将几个dt_draw_flag值组合在一起:
dim lMyFlags As DT_DRAW_FLAG
lMyFlags = DT_CENTER OR DT_VCENTER OR DT_RTLREADING
这将导致lmyflags = 131077
现在测试是否在这样的组合标志值中包含某个标志,我会执行以下操作:
If (131077 And DT_RTLREADING) = DT_RTLREADING Then
'DT_RTLREADING is contained.
Else
'DT_RTLREADING is NOT contained.
End Enum
我将如何在vb.net中执行此操作?
我是否仍然必须使用这种“纯数学”方法,还是有类似的方法……
lMyFlags.ContainsEnum(DT_RTLREADING)
我还没有找到?
谢谢你!
In VB6 I combine several DT_DRAW_FLAG values like this:
dim lMyFlags As DT_DRAW_FLAG
lMyFlags = DT_CENTER OR DT_VCENTER OR DT_RTLREADING
This would result in lMyFlags = 131077
Now to test if a certain flag is contained in such a combine flags value, I would do the following:
If (131077 And DT_RTLREADING) = DT_RTLREADING Then
'DT_RTLREADING is contained.
Else
'DT_RTLREADING is NOT contained.
End Enum
How would I do this in VB.NET?
Do I still have to use this "pure math" approach, or is there a method like...
lMyFlags.ContainsEnum(DT_RTLREADING)
... which I have not found yet?
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您有这样的枚举声明
,那么您可以使用hasflag来执行逻辑,
重要的一点是单个枚举值是两个的幂。
If you have an enum declaration like this
Then you can use HasFlag to do your logic
The important point here is that the single enum values are powers of two.
公认的答案很好,它有效。就您而言,您的枚举可能已经具有标志属性,因为它的三个功能的组合为2:2^0 = 1,2^2 = 4,而2^17 = 131072
您的枚举可能看起来像
< a href =“ https://learn.microsoft.com/en-us/dotnet/api/system.flagsattribute?view=net-6.0” rel =“ nofollow noreferrer”> flags
但是,无论它是否具有标志属性,您都可以使用位和钻头以相同的方式对其进行处理。我相信Hasflags函数只是位逻辑的速记:
它肯定是较少的代码。
请注意,您不会以所显示的方式结合枚举,而没有其他转换。使用位或这样做
,您可以使用enum.hasflag,无论您是否使用了标志属性。据我所知,该属性只是用来向消费者发出信号,表明这些值是两个的不同功能,并且可以在它们上执行位逻辑。标志属性严格没有任何事情,因此消费者有一些信任可以知道该怎么做(我们假设原始作者也知道它)
Accepted answer is good, it works. In your case, your Enum might already have the flags attribute, because it is a combination of three powers of 2: 2^0=1, 2^2=4, and 2^17=131072
Your enum may look like this
The Flags Attribute
However, whether or not it has the Flags attribute, you can treat it the same way using bitwise And. I believe the HasFlags function is just shorthand for the bitwise logic:
It is certainly less code.
Note, you don't combine enums in the way that you have shown, without some additional conversion. Use bitwise Or to do that
Also, you can use Enum.HasFlag regardless of whether you used the Flags Attribute. As far as I know, the attribute is just used to signal to the consumer that the values are distinct powers of two, and bitwise logic can be performed on them. There is nothing strictly going on with the flags attribute so there's some trust in the consumer to know what to do with it (and we assume the original author knew about it, too)