【发布时间】:2009-07-09 08:36:03
【问题描述】:
我们有一些可以导出为各种格式的东西。目前我们有这些格式由这样的枚举表示:
[Flags]
public enum ExportFormat
{
None = 0x0,
Csv = 0x1,
Tsv = 0x2,
Excel = 0x4,
All = Excel | Csv | Tsv
}
问题是这些必须枚举,并且它们还需要在 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)
r.Add("Comma Separated Values");
if ((e & ExportFormat.Tsv) == ExportFormat.Tsv)
r.Add("Tab Separated Values");
if ((e & ExportFormat.Excel) == ExportFormat.Excel)
r.Add("Microsoft Excel 2007");
return r.Join(", ");
}
也许这就是这样做的方法,但我觉得必须有更好的方法来做到这一点。我该如何重构它?
【问题讨论】:
-
你不需要本地化这些字符串吗?如果是这样,它们无论如何都会在资源文件中,因此将它们放在代码中的任何地方是没有意义的。
-
是的。但仍需要某种方式将资源键与枚举连接起来。