2009-07-09 75 views
1

我們有一些可能導出爲各種格式的東西。目前我們已經通過枚舉喜歡這代表這些格式:替換需要翻譯和枚舉的枚舉

[Flags] 
public enum ExportFormat 
{ 
    None = 0x0, 
    Csv = 0x1, 
    Tsv = 0x2, 
    Excel = 0x4, 
    All = Excel | Csv | Tsv 
} 

問題是,這些必須被枚舉,他們還需要在用戶界面翻譯或說明。目前我通過創建兩個擴展方法解決了這個問題他們工作,但我真的不喜歡他們或解決方案...他們覺得有點臭。問題是我真的不知道如何做得更好。有沒有人有任何好的選擇?這兩種方法:

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(", "); 
    } 

也許這是這樣做的方式,但我有一種感覺,必須有更好的方法來做到這一點。我怎麼能重構這個?

+0

難道你不需要本地化這些字符串嗎?如果是這樣,他們將會在資源文件中,所以將它們放在代碼中沒有意義。 – 2009-07-09 08:54:47

+0

是的。但仍然需要一些連接資源鍵和枚舉的方式。 – Svish 2009-07-09 09:28:45

回答

5

你可以使用格式方法中說明,以避免在多個地方做所有的位操作,像這樣:

private static Dictionary<ExportFormat, string> FormatDescriptions = 
    new Dictionary<ExportFormat,string>() 
{ 
    { ExportFormat.Csv, "Comma Separated Values" }, 
    { ExportFormat.Tsv, "Tab Separated Values" }, 
    { ExportFormat.Excel, "Microsoft Excel 2007" },    
}; 

public static string Describe(this ExportFormat e) 
{ 
    var formats = e.Formats(); 
    var descriptions = formats.Select(fmt => FormatDescriptions[fmt]); 

    return string.Join(", ", descriptions.ToArray()); 
} 

這樣一來,很容易從外部源或本地化結合的字符串描述如上所示。

1

我唯一想到的另一種方法是使用System.Attribute類。

public class FormatDescription : Attribute 
{ 
    public string Description { get; private set; } 

    public FormatDescription(string description) 
    { 
     Description = description; 
    } 
} 

然後在Describe函數中使用Reflection。 這種方法的唯一好處是在一個地方進行定義和描述。

+0

您可能希望在運行時緩存查找,因爲它們不會更改,並且使用反射來重複調用Describe將會代價高昂。 – adrianbanks 2009-07-09 09:11:52

+0

雖然這將很難本地化,不是嗎?因爲據我所知,當使用屬性時,你不能真正查找資源字符串等。 – Svish 2009-07-09 09:30:22

0

杜佩:How do I have an enum bound combobox with custom string formatting for enum values?

你可以寫,讀取指定的屬性,看看他們在你的資源的類型轉換器。因此,您可以毫不費力地獲得顯示名稱的多語言支持。

查看TypeConverter的ConvertFrom/ConvertTo方法,並使用反射讀取枚舉字段上的屬性。

增加:

滾動在鏈接的職位,做什麼是需要全面支持的一部分類型轉換器的實現了。

這將支持您同時具有多種語言的應用程序,不僅代碼名稱 - >英文名稱。

請記住,這只是顯示名稱,絕不是存儲值。您應該始終存儲代碼名稱或整數值,以支持使用相同數據的具有不同語言環境的用戶。