get value from c# enums

后端 未结 6 2033
无人共我
无人共我 2021-01-18 05:39

I have an enum

public enum ProductionStatus {
    Received = 000,
    Validated = 010,
    PlannedAndConverted = 020,
    InProduction = 030,
    QAChecked          


        
6条回答
  •  再見小時候
    2021-01-18 06:03

    Here is universal helper class that will do reverse action - getting key by value from ANY Enum:

    public static class EnumHelpers {
    
      public static T GetEnumObjectByValue(int valueId) {
        return (T) Enum.ToObject(typeof (T), valueId);
      }
    
    }
    

    And it works like this - given we have this Enum:

    public enum ShipmentStatus {
      New = 0,
      Shipped = 1,
      Canceled = 2
    }
    

    So, to get Enum object ShipmentStatus.Shipped this will return this object:

    var enumObject = EnumHelpers.GetEnumObjectByValue(1);
    

    So basicaly you can stick any Enum object and get it by value:

    var enumObject = EnumHelpers.GetEnumObjectByValue(VALUE);
    

提交回复
热议问题