C# 如何在类型安全枚举中获取字段名
我已经在我们的解决方案中实现了,现在我想以字符串格式获取字段的名称。我如何做到这一点? 这是我的类型安全枚举类:C# 如何在类型安全枚举中获取字段名,c#,C#,我已经在我们的解决方案中实现了,现在我想以字符串格式获取字段的名称。我如何做到这一点? 这是我的类型安全枚举类: public sealed class Statuses { private readonly String _name; private static readonly Dictionary<string, Statuses> Instance = new Dictionary<string, Statuses>()
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;
}
用法:
[TestMethod]
public void TestGetStatusName()
{
var state = Statuses.Selected;
Assert.AreEqual("Selected", state.StateCode);
}
也许有更有效的方法,但我找到的解决方案是:
public string StateCode
{
get
{
return GetType()
.GetFields(BindingFlags.Public | BindingFlags.Static)
.First(f => f.FieldType == typeof (Statuses) && ToString() == f.GetValue(null).ToString())
.Name;
}
}
编辑:根据下面@Guvante的建议更改了答案,我将按照您提供的链接的方式,将字段名作为第二个字符串传入
private Statuses(string name, string description)
public static readonly Statuses Submitted = new Statuses("Submitted", "Submitted by user");
唯一的问题是,确保您始终使用描述或名称(在您的问题中,您使用的是描述)。可能重复我不完全确定您在这里提出的问题。。在c#中,枚举是
enum Blah{Blah1,Blah2}
。。。您希望StateCode从何而来?其中一个静态只读
已提交
/已选择
字段,它将报告“已提交”或“已选择”?老实说,获取变量名听起来是一种非常非常非常复杂的方法尝试此操作您想要变量名还是想要字段的简短形式?在这种情况下,它们是相同的,但确定它们的方法完全不同。例如,在您提供的链接中,它们向构造函数提供了两个字符串,即枚举的长短形式。Where(f=>f.FieldType==typeof(status)&&ToString()==f.GetValue(null.ToString())。Select(f.Name)。First()
是一种更简洁、更直接的方法。请注意,无需将值强制转换为状态
,因为ToString
是在对象
中定义的。
private Statuses(string name, string description)
public static readonly Statuses Submitted = new Statuses("Submitted", "Submitted by user");