亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

比較枚舉和整數

比較枚舉和整數

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 關注
  • 205 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號