为了账号安全,请及时绑定邮箱和手机立即绑定

比较枚举和整数

比较枚举和整数

C#
慕娘9325324 2021-11-07 20:07:24
请参考以下枚举public enum Fruit{ Apple = 1, Orange = 2, Banana= 3}public enum Color{ Orange = 1, Yellow = 2, Red= 3}现在我想用颜色映射水果。所以我实现了public enum FruitColor{ 1= 3, 2= 1, 3= 2}实现 FruitColor 时出现语法错误预期标识符如何解决这个问题?
查看完整描述

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


查看完整回答
反对 回复 2021-11-07
?
千巷猫影

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


查看完整回答
反对 回复 2021-11-07
?
婷婷同学_

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);


查看完整回答
反对 回复 2021-11-07
  • 3 回答
  • 0 关注
  • 184 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信