Getting Enum value via reflection

前端 未结 15 2512
梦如初夏
梦如初夏 2020-12-05 01:35

I have a simple Enum

 public enum TestEnum
 {
     TestOne = 3,
     TestTwo = 4
 }

var testing = TestEnum.TestOne;

And I want to retrieve

15条回答
  •  爱一瞬间的悲伤
    2020-12-05 02:19

    For your requirement it's as simple as people already pointed it out. Just cast the enum object to int and you'd get the numeric value of the enum.

    int value = (int) TestEnum.TestOne;
    

    However, if there is a need to mix-down enum values with | (bitwise OR) e.g.

    var value = TestEnum.TestOne | TestEnum.TestTwo;
    

    and you wish to get what options that mixed-down value represents, here is how you could do it (note: this is for enums that represented by int values intended to take advantage of bitwise operatations) :

    first, get the enum options along with their values in a dictionary.

    var all_options_dic = typeof(TestEnum).GetEnumValues().Cast().ToDictionary(k=>k.ToString(), v=>(int) v);
    
    
    

    Filter the dictionary to return only the mixed-down options.

    var filtered = all_options_dic.Where(x => (x.Value & (int) options) != 0).ToDictionary(k=>k.Key, v=>v.Value);
    

    do whatever logic with your options. e.g. printing them, turning them to List, etc..:

    foreach (var key in filtered.Keys)
            {
                Console.WriteLine(key + " = " + filtered[key]);
            }
    

    hope this helps.

    提交回复
    热议问题