在帖子Enum ToString中,描述了一个方法来使用自定义属性,DescriptionAttribute如下所示:
Enum HowNice {
[Description("Really Nice")]
ReallyNice,
[Description("Kinda Nice")]
SortOfNice,
[Description("Not Nice At All")]
NotNice
}
Run Code Online (Sandbox Code Playgroud)
然后,GetDescription使用如下语法调用函数:
GetDescription<HowNice>(NotNice); // Returns "Not Nice At All"
Run Code Online (Sandbox Code Playgroud)
但是,当我想简单地使用枚举值填充ComboBox时GetDescription,这并没有真正帮助我,因为我不能强制ComboBox调用.
我想要的是有以下要求:
(HowNice)myComboBox.selectedItem将返回所选值作为枚举值.NotNice,用户不会看到" Not Nice At All" 而是看到" ".显然,我可以为我创建的每个枚举实现一个新类,并覆盖它ToString(),但这对每个枚举来说都是很多工作,我宁愿避免这样做.
有任何想法吗?
我正在尝试了解如何在阅读我的其他问题的答案后使用类型转换器.但我不确定我是否完全明白了......
在我的特定情况下,我想通过根据枚举成员获取资源字符串来将枚举成员"转换"为本地化字符串.所以,例如,如果我有这个枚举:
public enum Severity
{
Critical,
High,
Medium,
Low
}
Run Code Online (Sandbox Code Playgroud)
或这个:
public enum Color
{
Black = 0x0,
Red = 0x1,
Green = 0x2,
Blue = 0x4,
Cyan = Green | Blue,
Magenta = Red | Blue,
Yellow = Red | Green,
White = Red | Green | Blue,
}
Run Code Online (Sandbox Code Playgroud)
如何创建可以将这些成员转换为本地化字符串的类型转换器?我将如何使用它?目前我需要在WinForms应用程序中使用它,但也欢迎更一般的例子.