2010-12-02 81 views
1

在我的應用程序中,我有一些信息可以是一小組值中的一個 - 所以我想用enum來保存它,確保編譯時通過類型安全的有效值:我應該如何封裝這個多維枚舉?

public enum Something { A1, A2, A3, B1, B2, C1 }; 

這些枚舉代表多維數據(它們在上面的例子中有一個字母和一個數字),所以我希望能夠獲得與它們相關的值,例如

Something example = Something.A1; 
// Now I want to be able to query the values for example: 
example.Letter; // I want to get "A" 
example.Number; // "1"I want to get 1 

我有兩個可能的解決方案,他們都沒有覺得很「乾淨」,所以我很感興趣,這人喜歡,爲什麼呢,或者是否有人有更好的想法。

選項1: 創建一個包裝枚舉的結構,併爲包裝的數據提供屬性,例如,

public struct SomethingWrapper 
{ 
    public Something Value { get; private set; } 

    public SomethingWrapper(Something val) 
    { 
     Value = val; 
    } 

    public string Letter 
    { 
     get 
     { 
      // switch on Value... 
     } 
    } 

    public int Number 
    { 
     get 
     { 
      // switch on Value... 
     } 
    } 
} 

選項2: 離開枚舉,因爲它是和創建一個靜態輔助類,它提供了獲取值靜態函數:

public static class SomethingHelper 
{ 
    public static string Letter(Something val) 
    { 
     // switch on val parameter 
    } 

    public static int Number(Something val) 
    { 
     // switch on val parameter 
    } 
} 

我應該選擇哪一個,爲什麼?還是有沒有更好的解決方案,我沒有想到?

回答

4

第三種選擇:像第二個選項,但擴展方法:

public static class SomethingHelper 
{ 
    public static string Letter(this Something val) 
    { 
     // switch on val parameter 
    } 

    public static int Number(this Something val) 
    { 
     // switch on val parameter 
    } 
} 

然後,你可以這樣做:

Something x = ...; 
string letter = x.Letter(); 

這是不幸的,有沒有擴展屬性,但生活就是這樣。

或者,創建自己的僞枚舉:是這樣的:

public sealed class Something 
{ 
    public static Something A1 = new Something("A", 1); 
    public static Something A2 = ...; 

    private Something(string letter, int number) 
    { 
     Letter = letter; 
     Number = number; 
    } 

    public string Letter { get; private set; } 
    public int Number { get; private set; } 
} 
+0

我喜歡你第一個選項,但你的第二個選項將允許你創建一個像C3,除非添加了很多檢查代碼。 – 2010-12-02 21:36:31

0

爲什麼不只是使用兩個枚舉,並可能定義一個結構來保存每個枚舉?

+0

的結構將需要大量的檢查代碼,以確保無效的值並沒有被創造(B3,C2,C3在我的例子如果你使用A,B,C作爲一個枚舉並且使用1,2,3作爲枚舉)。 – 2010-12-02 21:41:00