3 回答
![?](http://img1.sycdn.imooc.com/5458657e000125a302200220-100-100.jpg)
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
![?](http://img1.sycdn.imooc.com/54586453000163bd02200220-100-100.jpg)
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
![?](http://img1.sycdn.imooc.com/533e4c0500010c7602000200-100-100.jpg)
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 关注
- 184 浏览
添加回答
举报