.NET 中的标志枚举
我正在尝试使用一组条件语句来设置带有 [Flags] 的枚举。 然而,编译器抱怨“m”未分配。 我如何重写以下内容以实现我的预期功能?
Media m;
if (filterOptions.ShowAudioFiles)
m = m | Media.Audio;
if (filterOptions.ShowDocumentFiles)
m = m | Media.Document;
if (filterOptions.ShowImageFiles)
m = m | Media.Image;
if (filterOptions.ShowVideoFiles)
m = m | Media.Video;
I am trying to use a set of conditional statements that will set up an enumeration attributed with [Flags]. However, the compiler complains that 'm' is unassigned. How can I rewrite the following to achieve my intended functionality?
Media m;
if (filterOptions.ShowAudioFiles)
m = m | Media.Audio;
if (filterOptions.ShowDocumentFiles)
m = m | Media.Document;
if (filterOptions.ShowImageFiles)
m = m | Media.Image;
if (filterOptions.ShowVideoFiles)
m = m | Media.Video;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
您需要初始化 m。 创建一个值为 0 的“None”标志,然后:
然后是其余代码。
You need to initialize m. Create a "None" flag that has value 0 then:
Then the rest of your code.
您还可以编写:
在您不知道枚举、类或它是否是值/引用类型的情况下很有用。
You could also write:
Useful in cases where you don't know the enum, class, or whether it's a value/reference type.
如果没有一个条件为真,则 m 将是未定义的。 将其设置为初始值。
If none of the conditions are true m will be undefined. Set it to an initial value.
你有像filterOptions.ShowNone这样的“默认”吗? 如果是这样,首先将 m 设置为该值。 编译器会抱怨,因为在所有 if 的末尾, m 可能没有设置为任何值。
Do you have a 'default' like filterOptions.ShowNone? If so, start off with m set to that. The compiler is complaining becuase at the end of all the if's, m might not be set to anything.
除了上面的答案之外,除了这段代码看起来相当多余这一事实之外,我还想建议您使用 Select Case 而不是所有那些丑陋的 If。
In addition to the above answers, besides the fact that this code seems pretty redundant, I'd like to suggest that you use a Select Case instead of all those ugly If's.
接受的方法的问题是,您需要有一个默认元素。
如果您不想使用
None
元素,则可以使用可空性。The Problem with the accepted approach is, that you need to have a default element.
In case you do not want to have the
None
element, then you can use nullability.您实际上并不需要创建
Media.None
。 您可以将任何值转换为 Flag 枚举,即使它不等于标志的值。You don't really need to create a
Media.None
. You can cast any value to the Flag enum even if it doesn't equal to a value of the flags.