.net FlagsAttribute枚举是否需要手动设置值? [英] Do .net FlagsAttribute enums need to be manually valued?
问题描述
为了在显示新闻故事的方法上允许使用不同的格式选项,我创建了一个枚举,可以将其传递以指定其显示方式.
To allow for different formatting options on a method that displays a news story, I've created an enumeration that can be passed in to specify how it gets displayed.
[Flags]
private enum NewsStyle
{
Thumbnail = 0,
Date = 1,
Text = 2,
Link = 4,
All = 8
}
string FormatNews( DataRow news, NewsStyle style )
{
StringBuilder HTML = new StringBuilder();
// Should the link be shown
if ( ((newsStyle & NewsStyle.All) == NewsStyle.All || (newsStyle & NewsStyle.Link) == NewsStyle.Link))
{
HTML.AppendFormat("<a style=\"text-decoration:none; color: rgb(66, 110, 171);\" href=\"ViewStory.aspx?nsid={0}\">",
UrlEncode(newsStory["NewsStoryID"].ToString()));
}
// Etc etc...
}
// So to call the method...
Response.Write( FormatNews( news, NewsStyle.Date | NewsStyle.Text ) );
问题是,只有手动在枚举上指定值时,我才能使代码正常工作,否则按位枚举检查操作将无法正常工作.
The problem is that I can only get the code to work if I manually specify the values on the enum, otherwise the bitwise enum checking operation doesn't work correctly.
我一直遵循让.net处理将值分配给枚举的规则-这是真正的例外吗?
I've always followed the rule of let .net handle the assigning of values to enums - is this a geniuine exception?
推荐答案
是的,这是一个真正的例外.默认情况下,枚举是从0开始分配的值,每个值都比以前的值高1,而与任何 FlagsAttribute
无关.(当您手动指定一些值时,当然还有更复杂的规则-请参见 MSDN文档)
Yes, it is a genuine exception. Enumerations are by default assigned values from 0 onwards, each one 1 higher than the previous value, regardless of any FlagsAttribute
s. (There of course are more elaborate rules for when you specify some values manually – see the MSDN docs)
虽然确实有一点意义是有意义的,让标志枚举自动获取以2的幂表示的值,但我知道为什么最好不这样做的原因:
While it does somewhat make sense to have a flags enumeration automatically get values in powers of two, I see reasons why it's probably best not to do so:
拥有这样的枚举是完全合理的:
It's perfectly reasonable to have an enum like this:
[Flags]
enum Foo
{
None,
Bar,
Baz,
BarAndBaz
}
这当然要求值必须为0、1、2和3才有意义.
This of course requires the values to be 0, 1, 2 and 3 to be sensible.
让一个纯属的属性改变一段C#代码的全部含义是很违反直觉的.考虑我的 Foo
示例枚举.是否应该允许通过删除 Flags
属性来通过静默更改枚举器值来破坏代码?
It'd be pretty counter-intuitive to let the presence of a mere attribute change the entire meaning of a piece of C# code. Consider my Foo
example enumeration. Should removing the Flags
attribute be allowed to break the code by silently changing the enumerator values?
这篇关于.net FlagsAttribute枚举是否需要手动设置值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!