简体   繁体   中英

How to set two values for same definition in enum, C#

I am trying to compare values that I am getting from web service, but sometimes I get int value, sometimes i get string. So it would be great that i could only check for Type.value1.

for example:

enum Type { value1 = 1 , value1="one"}

and like that for more value2, etc... But of course, I cannot do this because it I cannot add two definitons for value1.

Sometimes a type that behaves mostly like an enum but has some richer behaviour can be very useful:

public sealed class MyFakeEnum {

  private MyFakeEnum(int value, string description) {
    Value = value;
    Description = description;
  }

  public int Value { get; private set; }

  public string Description { get; private set; }

  // Probably add equality and GetHashCode implementations too.

  public readonly static MyFakeEnum Value1 = new MyFakeEnum(1, "value1");
  public readonly static MyFakeEnum Value2 = new MyFakeEnum(2, "value2");
}

You can consider adding attributes to the enums and use reflection.

enum Type 
{ 
    [Description("One")]
    value1 = 1 
}

I also make use of using decorating the enum with a description attribute as described by BSoD_ZA. But I would suggest that you then implement an extension method for the enumeration to obtain the string description for example:

public static class EnumExtension
{

  public static string ToDescription<TEnum>(this TEnum enumValue) where TEnum : struct
  {
    return ReflectionService.GetClassAttribute<DescriptionAttribute>(enumValue);
  }
}

enum Type 
{ 
  [Description("One")]
  value1 = 1 
}

var value = Type.Value1;
Console.Writeline(value.ToDescription());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM