简体   繁体   中英

How to get field name in type safe enum

I have implemented the Type safe enum pattern in our solution, and now I want to get the name of the fields in string format. How do I achieve that? This is my type safe enum class:

    public sealed class Statuses
    {
      private readonly String _name;
      private static readonly Dictionary<string, Statuses> Instance 
= new Dictionary<string, Statuses>();

      private Statuses(string name)
      {
          _name = name;

          Instance[name] = this;
      }

      public static explicit operator Statuses(string str)
      {
          Statuses result;
          if (Instance.TryGetValue(str, out result))
              return result;
          else
              throw new InvalidCastException();
      }


     public static readonly Statuses Submitted = new Statuses("Submitted by user");
     public static readonly Statuses Selected = new Statuses("Selected by user");

     public static IEnumerable<Statuses> AllStatuses
    {
        get
        {
            return Instance.Values;

        }
    }
    public override String ToString()
    {
        return _name;
    }

And I would like to add a property to return the name of the current field like this:

 public string StateCode
        {
            get
            {
                return //The current fields name
            }
        }

Usage:

[TestMethod]
public void TestGetStatusName()
{
var state = Statuses.Selected;
Assert.AreEqual("Selected", state.StateCode);            
}

There might be some more effective way, but this is the solution i found:

public string StateCode
{
    get
    {
        return GetType()
            .GetFields(BindingFlags.Public | BindingFlags.Static)
            .First(f => f.FieldType == typeof (Statuses) && ToString() == f.GetValue(null).ToString())
            .Name;
    }
}

Edit: changed the answer according to the suggestion below by @Guvante

I would follow the way that the link you gave did, pass in the field name as a second string.

private Statuses(string name, string description)

public static readonly Statuses Submitted = new Statuses("Submitted", "Submitted by user");

The only problem then becomes ensuring you are consistently using either the description or the name (in your question you are using the description).

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