除了 enum 之外,c# 还可以使用什么
因此,目前有一个用于应用程序状态的枚举。然而,在用户界面上使用它时,感觉有些不对劲。填充下拉列表时整数和字符串之间的许多转换。我可以使用扩展方法或类型转换器,并继续使用枚举,如果枚举中有多个单词,这将很有帮助。
我想在我把它挖得很深之前,我想先看看是否可以填补一个可能的洞。
谢谢。
So currently have an enumeration used on the status of an application. However, something feels off when using it against the ui. To many conversions between integer and string when populating drop downs. I could use an extension method or the type converter and continue to use the enum which will be helpful if an enum has multiple words in it.
Thought I'd ask to see about filling in a possible hole before I dig it to deep.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我的团队在最近的项目中遇到了这个问题。我们保留了枚举,因为它们是用于已知常量值的有限列表的东西,但我们做了一些事情以使它们对开发人员更加友好:
因此,考虑到以下情况:
我们可以在两行中用用户友好的选择填充 DropDownList:
...然后我们可以使用非常可读的代码解析选择:
编辑:我被要求提供 GetDescription() 方法。我对分享整个事情有点犹豫,但这是获取装饰枚举常量的描述属性的基本算法。解析 CamelCased 名称是非常简单的正则表达式对大写字母的拆分,无论如何我们的实现有点天真。此代码片段需要 System.ComponentModel.DescriptionAttribute (它也是枚举常量的装饰器),并且 enumType 是扩展方法的“this”参数,类型为 Enum:
My team had this issue in our recent project. We kept the enums, because they are the thing to use for a finite list of known constant values, but we did a few things to make them more developer-friendly:
So, given the following:
we could populate a DropDownList with user-friendly choices in two lines:
... and then we could parse the selection back out with very readable code:
EDIT: I have been asked for the GetDescription() method. I'm a little iffy about sharing the whole thing, but here's the basic algorithm for getting a Description attribute that decorates an enum constant. Parsing a CamelCased name is pretty straightforward RegEx splits on capital letters, and our implementation's a little naive anyway. This snippet requires System.ComponentModel.DescriptionAttribute (which is also the decorator for the enum constants), and enumType is the "this" parameter of the extension method, of type Enum:
如果您使用的变量具有有限且众所周知的可能状态数量,那么枚举确实是您可以使用的正确构造。有许多可能的方法可以使 UI 的使用更加方便,并且您引用了两个很好的方法,它们是类型转换器和扩展方法。
If you are working with a variable that has a finite and well-known number of possible states, then an enum is indeed the correct construct for you to use. There are many possible ways to make working with the UI more convenient, and you have cited two excellent ones, which are type converters and extension methods.
类似枚举的构造绝对是正确的选择。如果由于某种原因您不想使用熟悉的内置方式,您可以使用自己的工具来实现更多功能。这是基本思想:
有一个设计模式,但我忘记了名字。
An Enum like construct is definitely the right choice. If for some reason you don't want to use the familiar built in way, you can make you're own with a bir more functionaliy. here's the basic idea:
There's a design pattern for this, but I forget the name.