相关疑难解决方法(0)

如何为enum值设置枚举绑定组合框以及自定义字符串格式?

在帖子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(),但这对每个枚举来说都是很多工作,我宁愿避免这样做.

有任何想法吗?

哎呀,我甚至会一个拥抱作为赏金:-)

c# enums combobox

134
推荐指数
8
解决办法
8万
查看次数

替换需要翻译和枚举的枚举

我们有一些东西可以导出成各种格式.目前我们有这样的格式由枚举表示如下:

[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)

c# enums

1
推荐指数
1
解决办法
2279
查看次数

标签 统计

c# ×2

enums ×2

combobox ×1