String representation of an Enum

2018-12-31 04:55发布

I have the following enumeration:

public enum AuthenticationMethod
{
    FORMS = 1,
    WINDOWSAUTHENTICATION = 2,
    SINGLESIGNON = 3
}

The problem however is that I need the word "FORMS" when I ask for AuthenticationMethod.FORMS and not the id 1.

I have found the following solution for this problem (link):

First I need to create a custom attribute called "StringValue":

public class StringValue : System.Attribute
{
    private readonly string _value;

    public StringValue(string value)
    {
        _value = value;
    }

    public string Value
    {
        get { return _value; }
    }

}

Then I can add this attribute to my enumerator:

public enum AuthenticationMethod
{
    [StringValue("FORMS")]
    FORMS = 1,
    [StringValue("WINDOWS")]
    WINDOWSAUTHENTICATION = 2,
    [StringValue("SSO")]
    SINGLESIGNON = 3
}

And of course I need something to retrieve that StringValue:

public static class StringEnum
{
    public static string GetStringValue(Enum value)
    {
        string output = null;
        Type type = value.GetType();

        //Check first in our cached results...

        //Look for our 'StringValueAttribute' 

        //in the field's custom attributes

        FieldInfo fi = type.GetField(value.ToString());
        StringValue[] attrs =
           fi.GetCustomAttributes(typeof(StringValue),
                                   false) as StringValue[];
        if (attrs.Length > 0)
        {
            output = attrs[0].Value;
        }

        return output;
    }
}

Good now I've got the tools to get a string value for an enumerator. I can then use it like this:

string valueOfAuthenticationMethod = StringEnum.GetStringValue(AuthenticationMethod.FORMS);

Okay now all of these work like a charm but I find it a whole lot of work. I was wondering if there is a better solution for this.

I also tried something with a dictionary and static properties but that wasn't better either.

标签: c# enums
30条回答
时光乱了年华
2楼-- · 2018-12-31 05:19

Very simple solution to this with .Net 4.0 and above. No other code is needed.

public enum MyStatus
{
    Active = 1,
    Archived = 2
}

To get the string about just use:

MyStatus.Active.ToString("f");

or

MyStatus.Archived.ToString("f");`

The value will be "Active" or "Archived".

To see the different string formats (the "f" from above) when calling Enum.ToString see this Enumeration Format Strings page

查看更多
怪性笑人.
3楼-- · 2018-12-31 05:19

If you've come here looking to implement a simple "Enum" but whose values are strings instead of ints, here is the simplest solution:

    public sealed class MetricValueList
    {
        public static readonly string Brand = "A4082457-D467-E111-98DC-0026B9010912";
        public static readonly string Name = "B5B5E167-D467-E111-98DC-0026B9010912";
    }

Implementation:

var someStringVariable = MetricValueList.Brand;
查看更多
听够珍惜
4楼-- · 2018-12-31 05:21

Here is yet another way to accomplish the task of associating strings with enums:

struct DATABASE {
    public enum enums {NOTCONNECTED, CONNECTED, ERROR}
    static List<string> strings =
        new List<string>() {"Not Connected", "Connected", "Error"};

    public string GetString(DATABASE.enums value) {
        return strings[(int)value];
    }
}

This method is called like this:

public FormMain() {
    DATABASE dbEnum;

    string enumName = dbEnum.GetString(DATABASE.enums.NOTCONNECTED);
}

You can group related enums in their own struct. Since this method uses the enum type, you can use Intellisense to display the list of enums when making the GetString() call.

You can optionally use the new operator on the DATABASE struct. Not using it means the strings List is not allocated until the first GetString() call is made.

查看更多
后来的你喜欢了谁
5楼-- · 2018-12-31 05:22

When I'm confronted with this problem, there are a couple of questions that I try to find the answers to first:

  • Are the names of my enum values sufficiently friendly for the purpose, or do I need to provide friendlier ones?
  • Do I need to round-trip? That is, will I need to take text values and parse them into enum values?
  • Is this something I need to do for many enums in my project, or just one?
  • What kind of UI elements will I be presenting this information in - in particular, will I be binding to the UI, or using property sheets?
  • Does this need to be localizable?

The simplest way to do this is with Enum.GetValue (and support round-tripping using Enum.Parse). It's also often worth building a TypeConverter, as Steve Mitcham suggests, to support UI binding. (It's not necessary to build a TypeConverter when you're using property sheets, which is one of the nice things about property sheets. Though lord knows they have their own issues.)

In general, if the answers to the above questions suggest that's not going to work, my next step is to create and populate a static Dictionary<MyEnum, string>, or possibly a Dictionary<Type, Dictionary<int, string>>. I tend to skip the intermediate decorate-the-code-with-attributes step because what's usually coming down the pike next is the need to change the friendly values after deployment (often, but not always, because of localization).

查看更多
何处买醉
6楼-- · 2018-12-31 05:22

If you think about the problem we're trying to solve, it's not an enum we need at all. We need an object that allows a certain number of values to be associated with eachother; in other words, to define a class.

Jakub Šturc's type-safe enum pattern is the best option I see here.

Look at it:

  • It has a private constructor so only the class itself can define the allowed values.
  • It is a sealed class so values can't be modifed through inheritence.
  • It is type-safe, allowing your methods to require only that type.
  • There is no reflection performance hit incurred by accessing the values.
  • And lastly, it can be modified to associate more than two fields together, for example a Name, Description, and a numeric Value.
查看更多
唯独是你
7楼-- · 2018-12-31 05:23

old post but...

The answer to this may actually be very simple. Use Enum.ToString() function

There are 6 overloads of this function, you can use Enum.Tostring("F") or Enum.ToString() to return the string value. No need to bother with anything else. Here is a working Demo

Note that this solution may not work for all compilers (this demo does not work as expected) but at least it works for the latest compiler.

查看更多
登录 后发表回答