3 回答

TA貢獻1831條經驗 獲得超9個贊
使用 anenum
來映射枚舉值毫無意義。我會用字典:
Dictionary<Fruit, Color> FruitToColor = new Dictionary<Fruit, Color> { { Fruit.Apple, Color.Red } , { Fruit.Orange, Color.Orange } , { Fruit.Banana, Color.Yellow } }; Color colorOfBanana = FruitToColor[Fruit.Banana]; // yields Color.Yellow

TA貢獻1829條經驗 獲得超7個贊
也只是把它放在那里,因為我可以,唯一的好處是你可以在自定義屬性中編碼其他數據。但是,我會使用字典或開關;)
給定的
public enum MyFruit
{
[MyFunky(MyColor.Orange)]
Apple = 1,
[MyFunky(MyColor.Yellow)]
Orange = 2,
[MyFunky(MyColor.Red)]
Banana = 3
}
public enum MyColor
{
Orange = 1,
Yellow = 2,
Red = 3
}
public static class MyExteions
{
public static MyColor GetColor(this MyFruit fruit)
{
var type = fruit.GetType();
var memInfo = type.GetMember(fruit.ToString());
var attributes = memInfo[0].GetCustomAttributes(typeof (MyFunkyAttribute), false);
if (attributes.Length > 0)
return ((MyFunkyAttribute)attributes[0]).Color;
throw new InvalidOperationException("blah");
}
}
public class MyFunkyAttribute : Attribute
{
public MyFunkyAttribute(MyColor color) { Color = color;}
public MyColor Color { get; protected set; }
}
用法
var someFruit = MyFruit.Apple;
var itsColor = someFruit.GetColor();
Console.WriteLine("Fruit = " + someFruit + ", Color = " + itsColor);
輸出
Fruit = Apple, Color = Orange

TA貢獻1844條經驗 獲得超8個贊
成員標識符不允許以數值開頭,但是您可以使用一種方法從每個值中獲取正確的值enum:
public Fruit GetFruit(this Color c) {
switch ((int)c) {
case 1: return (Fruit)3;
case 2: return (Fruit)2;
case 3: return (Fruit)1;
}
return 0;
}
這種方法的逆過程會給你Color來自Fruit. 您可以通過Color類型調用此方法作為靜態方法:
Fruit myFruit = Color.GetFruit(Color.Orange);
- 3 回答
- 0 關注
- 205 瀏覽
添加回答
舉報