枚举范围可能吗? [英] are ranges possible with enums?
问题描述
在C#中,您可以在枚举类型中使用数字范围吗?
In C#, can you use number ranges in enum types, for example
public enum BookType
{
Novel = 1,
Journal = 2,
Reference = 3,
TextBook = 4 .. 10
}
编辑:之所以需要这样做,是因为将数字转换为枚举类型,例如:
The reason this is needed is to cast from a number to the enum type, eg:
int iBook = 5
BookType btBook = (BookType)ibook
Debug.Print "Book " + ibook + " is a " btBook
,预期输出为:书5是教科书
and the expected output is: Book 5 is a TextBook
推荐答案
根据C#标准(p612,C#编程语言),赋予枚举的值必须为常量整数(或任何类似的类型-long,byte,sbyte,short等),因此值的范围无效。
According to the C# standard (p612, The C# Programming Language) the value given to an enumeration must be a constant integer (or any similar type - long, byte, sbyte, short, etc), so a range of values isn't valid.
我的编译器(VS2008)符合规范。
My compiler (VS2008) agrees with the spec.
由于您无法在枚举中重复名称,因此获得的最接近的内容是这样的:
Since you can't repeat names within an enumeration, the closest you'll get is something like this:
public enum BookType
{
Novel = 1,
Journal = 2,
Reference = 3,
TextBook4 = 4,
TextBook5 = 5, ...
TextBook10 = 10
}
这实际上很丑。也许枚举不是解决您特定问题的方法...
Which is actually pretty ugly. Perhaps an enum is not the solution to your particular problem ...
这篇关于枚举范围可能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!