2010-12-02 79 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