在帖子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(),但这对每个枚举来说都是很多工作,我宁愿避免这样做.
有任何想法吗?
我们有一些东西可以导出成各种格式.目前我们有这样的格式由枚举表示如下:
[Flags]
public enum ExportFormat
{
None = 0x0,
Csv = 0x1,
Tsv = 0x2,
Excel = 0x4,
All = Excel | Csv | Tsv
}
Run Code Online (Sandbox Code Playgroud)
问题是必须枚举这些,并且它们还需要在ui中进行翻译或描述.目前我通过创建两个扩展方法解决了这个问题 他们工作,但我真的不喜欢他们或解决方案......他们觉得有点臭.问题是我真的不知道如何做得更好.有没有人有任何好的选择?这是两种方法:
public static IEnumerable<ExportFormat> Formats(this ExportFormat exportFormats)
{
foreach (ExportFormat e in Enum.GetValues(typeof (ExportFormat)))
{
if (e == ExportFormat.None || e == ExportFormat.All)
continue;
if ((exportFormats & e) == e)
yield return e;
}
}
public static string Describe(this ExportFormat e)
{
var r = new List<string>();
if ((e & ExportFormat.Csv) == ExportFormat.Csv) …Run Code Online (Sandbox Code Playgroud)