2015-10-07 157 views
2

我可以在C#中爲枚舉值名稱制作別名嗎? 比如我有兩個文件:A和B.C#中枚舉值名稱的別名

public class A 
{ 
    public enum myEnum 
     { 
      value_1, 
      value_2 
     }; 
} 

而且我要在B級使用此枚舉:

public class B 
{ 
private A.myEnum[] tab = { A.myEnum.value_1, A.myEnum.value_2, A.myEnum.value_1 ..} 

} 

我想爲一個別名: A.myEnum。 _1和A.myEnum.value_2 這樣我就可以寫

private A.myEnum[] tab = { alias_1, alias_2}, 
+1

你爲什麼不拉枚舉類A的外?那麼你不必使用類名。使用枚舉名稱並對其進行黑客攻擊是正常的,因此您沒有枚舉名稱可能會導致代碼混淆。 – juharr

+0

因爲我需要這個類的枚舉。加上它唯一的例子 – JohnT

+1

爲什麼你需要它在A中定義?如果你公開它並把它放在同一個命名空間中,你仍然可以在A中使用它。作爲例子,你可能已經描述了一個[XY問題](http://meta.stackexchange.com/questions/66377/what-the-xy-problem) – juharr

回答

3

我想我可能失去了一些東西,但:

public class B 
{ 
    private const A.myEnum alias_1 = A.myEnum.value_1; 
    private const A.myEnum alias_2 = A.myEnum.value_2; 

    private A.myEnum[] tab = {alias_1, alias_2}; 
} 
+0

謝謝,那就是我需要的。 – JohnT

0

使用像

public static myEnum GetEnumName(string str) 
{ 
    switch(str) 
    { 
     case "alias_1": return myEnum.Value_1; 
     case "alias_2": return myEnum.Value_2; 
     default: throw new Exception(); 
    } 
} 
0

一個輔助方法,你只可以得到所有的值,並把它們變成一個數組:

myEnum[] tab = Enum.GetValues(typeof(myEnum)).Cast<myEnum>().ToArray();