作为枚举的键值对
我可以有一个充当键值对的枚举吗?
public enum infringementCategory
{
Infringement,
OFN
}
如果我选择Infringement
,我应该得到“INF0001”,如果我选择OFN
,我应该得到“INF0002”
这可能吗?
Can I have an enum which acts as a key value pair.
public enum infringementCategory
{
Infringement,
OFN
}
If I select Infringement
I should get "INF0001" and if I select OFN
I should get "INF0002"
Is it possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以使用装饰器将字符串表示形式与枚举值关联起来。检查这个问题:带有用户友好字符串的Enum ToString
它看起来像:
看起来比使用字典更整洁,并且需要更少维持。
You can use decorators in order to associate string representation with your enum values. Check this question: Enum ToString with user friendly strings
It will look like:
Looks more neat than using Dictionary and needs less maintain.
这些扩展怎么样:
有了这个,你可以像这样构建你的枚举:
并像这样获取你的列表:
How about these extensions:
With this in place you can built up your enum like this:
And get your list like this:
您可以将标题 (INF0001)...存储在
Dictionary
中You could store the titles (INF0001)... in a
Dictionary<infringementCategory, string>
请参阅:
这里是扩展方法......
See:
And here the extension methods...
更新:
感谢 Oliver 指出 System.Component.DescriptionAttribute 。操作方法如下:
Update:
Thanks to Oliver for pointing out System.Component.DescriptionAttribute. Here's how to do it:
您有多种选择:
vc74 建议的字典。这是高效的,并且可以将枚举与属性解耦。
switch 语句
如果您只想与每个语句关联一个整数,则可以使用:
然后将
(int)myEnum
放入String.Format
中,将其转换为您想要的形式的字符串。属性
为了提高性能,您可以使用一次反射来填充字典。
You have a number of choices:
A Dictionary as vc74 suggested. This is efficient and decouples your enum from the property.
A switch statement
If the only thing you want to associate with each is an integer you can use:
and then put
(int)myEnum
intoString.Format
to turn it into a string of the form you want.An Attribute
For improved performance you can use reflection once to populate dictionary.