开发者

C# Enum Question

I need to make an enum with one of the values = 50/50

Is this not possible? Visual Studio doesn't seem to like it.

I may have to make this field a database lookup it seems.

Please le开发者_运维知识库t me know.


C# enumerations compile out as sealed classes, inheriting from Enum, with public static fields carrying the name of your enumeration members, thus, you're asking the compiler to name fields the enum values or 50/50 in your case.

Enumeration values carry the same restrictions as properties and fields when it comes to naming.


You can use the Description Attribute to store the custom value of the enum in the Description and then use it.

the Enum:

public enum MyEnum
{
    [Description("50/50")]
    Enum1 = 1,

    [Description("Whatever")]
    Enum2 = 2,
}

Method to read the custom value stored in Description attribute using reflection.

private static string GetEnumCustomValue(Enum value)
{
   FieldInfo enumField = value.GetType().GetField(value.ToString());
   var attributes = 
      (DescriptionAttribute[])enumField.GetCustomAttributes(typeof(DescriptionAttribute)), false);
   if (attributes.Length > 0)
   {
      return attributes[0].Description;
   }
   return value.ToString();
}


Yup, sure is possible

enum SomeEnum
{
    Value = 1 // 50/50!
}

Enum values are constant integral types.


If you want the NAME of your value to be 50/50, you're out of luck. You can however define a value whose name is FiftyFifty, which (in my opinion) is just as descriptive a name.


A "50/50" value? You mean a string value? No, C# cannot do that.


dhinesh give already a good tip by using the Description attribute.

I would recommend the following enum

public enum Chances
{
    [Description("No guess available")]
    NotDefined = 0,

    [Description("No chance")]
    None,

    [Description("50/50")]
    FiftyFifty,

    [Description("100%")]
    Always        
}

To get afterwards the description out of it you should take a look into these question:

  • How to get C# Enum description from value?
  • Data bind enum properties to grid and display description
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜