C#:有没有办法对枚举进行分类?
给定以下枚举:
public enum Position
{
Quarterback,
Runningback,
DefensiveEnd,
Linebacker
};
是否可以对命名常量进行分类,以便我可以将“四分卫”和“跑卫”标记为进攻位置,将“防守端”和“线卫”标记为防守位置?
Given the following enum:
public enum Position
{
Quarterback,
Runningback,
DefensiveEnd,
Linebacker
};
Is it possible to classify the named constants, such that I could mark 'Quarterback' and 'Runningback' as offensive positions and 'DefensiveEnd' and 'Linebacker' as defensive positions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
您可以使用属性:
然后在适当的
FieldInfo
上检查IsDefined
。语法不是很漂亮,但是您可以添加一些扩展方法以使事情更易于管理:You can use attributes:
And then check for
IsDefined
on an appropriateFieldInfo
. Syntax is not very pretty, but you can throw in a couple of extension methods to make things more manageble:为什么不接吻:
Why not KISS:
您可以使用属性,例如
CategoryAttribute
:You could use an attribute, like
CategoryAttribute
:您可以使用标志
You could use Flags
也许您可以尝试使用 typesefe 枚举模式
Maybe you can try to use typesefe enum pattern
您可以使用某种形式的标志位。但这可能会导致混乱。更好的方法可能是仅使用所需的详细信息创建自定义类,然后使用字典来查找每个职位类型;
...作为枚举...
You could use some form of flag bits. But that could lead to a mess. A better way may be to just create custom classes with the details you want and then use a Dictionary to lookup each position type;
... as enum ...
一种未充分利用(但完全有效)的技术是使用定义一组常量的类。作为一个类,您可以添加其他属性来描述枚举值的其他方面。奇怪的是,这是大多数枚举在 Java 中实现的方式(Java 没有专门的关键字)。
如果您走这条路,通常最好将类密封并定义私有构造函数,以便只有类本身可以定义实例。这是一个例子:
使用这样的枚举会产生比属性更优雅、更简单的语法:
An underutilized (but perfectly valid) technique is to use a class which defines a set of constants. As a class, you can add additional properties that can describe other aspects of the enumerated value. Curiously, this is the way most enums are implemented in Java (which doesn't have a special keyword for them).
If you go this route, it's generally a good idea to make the class sealed and define a private constructor, so that only the class itself can define instances. Here's an example:
Using such an enum results in more elegant and simpler syntax than attributes:
您可以在类中声明枚举:
请注意,防御值从 10 开始,以便值不会重叠。您没有说明为什么要这样做,因此这可能无法满足您的需求。
You can declare the enums in a class:
Note that the Defensive values start at 10 so that values don't overlap. You don't state why you want to do this, so this might not meet your needs.