如何在类型安全枚举中获取字段名称

时间:2015-04-20 15:31:33

标签: c#

我已在我们的解决方案中实现了Type safe enum pattern,现在我想以字符串格式获取字段的名称。我如何实现这一目标? 这是我的类型安全枚举类:

    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;
    }

我想添加一个属性来返回当前字段的名称,如下所示:

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

用法:

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

2 个答案:

答案 0 :(得分:1)

可能有一些更有效的方法,但这是我找到的解决方案:

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

编辑:根据@Guvante

的建议更改了答案

答案 1 :(得分:0)

我会按照您提供的链接的方式,将字段名称作为第二个字符串传递。

private Statuses(string name, string description)

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

唯一的问题就是确保您始终使用说明或名称(在您的问题中使用说明)。