开发者

string representation of an enum (estring)?

开发者 https://www.devze.com 2023-02-08 17:15 出处:网络
i need an enum or something similiar to do something like this: public enum MyStringEnum { [StringValue(\"Foo A\")] Foo = \"A\",

i need an enum or something similiar to do something like this:

public enum MyStringEnum { [StringValue("Foo A")] Foo = "A", [StringValue("Foo B")] Foo = "B" }

is this possible? my example, i return back a dataset with a value represented as either A,B,C,D,E .. i need a solution to 开发者_运维知识库return this as a string representation?

i guess the obvious would be to create an extension method or something which just had a switch statement in and return a string .. any other cleaner solutions?

regards, dave


Here is something we use for our MVC applications to retrieve a display name for our enums. It uses a custom attribute and an extension method to retrieve the enum display name.

[AttributeUsage(AttributeTargets.Field, AllowMultiple = false)]
public class EnumDisplayNameAttribute : Attribute
{
  public EnumDisplayNameAttribute(string displayName)
  {
    DisplayName = displayName;
  }

  public string DisplayName { get; set; }
}


public static string GetDisplayName(this Enum enumType)
{
  var displayNameAttribute = enumType.GetType()
                                     .GetField(enumType.ToString())
                                     .GetCustomAttributes(typeof(EnumDisplayNameAttribute), false)
                                     .FirstOrDefault() as EnumDisplayNameAttribute;

  return displayNameAttribute != null ? displayNameAttribute.DisplayName : Enum.GetName(enumType.GetType(), enumType);
}

Usage on the enum:

public enum Foo
{
  [EnumDisplayName("Foo Bar")]
  Bar = 0
}

Getting back the display name:

var f = Foo.Bar;
var name =  f.GetDisplayName();


Would it be an option not to use enum and use structs instead?

struct FooEnum
{
    private int value;
    private string name;
    private FooEnum(int value, string name)
    {
        this.name = name;
        this.value = value;
    }

    public static readonly FooEnum A = new FooEnum(0, "Foo A");
    public static readonly FooEnum B = new FooEnum(1, "Foo B");
    public static readonly FooEnum C = new FooEnum(2, "Foo C");
    public static readonly FooEnum D = new FooEnum(3, "Foo D");

    public override string ToString()
    {
        return this.name;
    }

    //TODO explicit conversion to int etc.
}

You could then use FooEnum like an enum with an own ToString() overload:

FooEnum foo = FooEnum.A;
string s = foo.ToString(); //"Foo A"


If you want to do something like this:

MyStringEnum value = MyStringEnum.A;
string description = value.GetDescription();
// description == "Foo A"

Setup your enum like this:

public enum MyStringEnum
{
    [Description("Foo A")]
    A,
    [Description("Foo B")]
    B
}

And use a utility/extension method that reads the attribute:

public static string GetDescription(this MyStringEnum enumerationValue)
{
    Type type = enumerationValue.GetType();
    string name = enumerationValue.ToString();

    //Tries to find a DescriptionAttribute for a potential friendly name for the enum
    MemberInfo[] member = type.GetMember(name);
    if (member != null && member.Length > 0)
    {
        object[] attributes = member[0].GetCustomAttributes(typeof(DescriptionAttribute), false);

        if (attributes != null && attributes.Length > 0)
        {
            //Pull out the description value
            return ((DescriptionAttribute)attributes[0]).Description;
        }
    }

    return name;
}


I've seen this done where I would put

MyStringEnum.Foo.ToString();

In this case it would give "A"


The cleanest solution for this problem is to create a custom attribute that will store the string value you want for the enum constant. I've used that strategy in the past and it worked out fairly well. Here's a blog post detailing the work involved:

Enum With String Values In C# - Stefan Sedich's Blog

Of course this is only necessary if you need some kind of meaningful text. If the name of the enum constant works for you...then you can simply call ToString().

0

精彩评论

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

关注公众号