-
天涯尽头无女友
使用 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
-
千巷猫影
也只是把它放在那里,因为我可以,唯一的好处是你可以在自定义属性中编码其他数据。但是,我会使用字典或开关;)给定的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
-
婷婷同学_
成员标识符不允许以数值开头,但是您可以使用一种方法从每个值中获取正确的值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);