我有这样的枚举:
public enum ObectTypes
{
TypeOne,
TypeTwo,
TypeThree,
...
TypeTwenty
}
然后我需要将这个枚举转换为字符串。现在我这样做:
public string ConvertToCustomTypeName(ObjectTypes typeObj)
{
string result = string.Empty;
switch (typeObj)
{
case ObjectTypes.TypeOne: result = "This is type T123"; break;
case ObjectTypes.TypeTwo: result = "Oh man! This is type T234"; break;
...
case ObjectTypes.TypeTwenty: result = "This is type last"; break;
}
return result;
}
我很确定有更好的方法来做到这一点,我正在寻找一些好的实践解决方案。
编辑:结果字符串中没有一个模式。
提前致谢。
最佳答案
我使用 System.ComponentModel
中的 [Description]
属性
例子:
public enum RoleType
{
[Description("Allows access to public information")] Guest = 0,
[Description("Allows access to the blog")] BlogReader = 4,
}
然后我会从中读取
public static string ReadDescription<T>(T enumMember)
{
var type = typeof (T);
var fi = type.GetField(enumMember.ToString());
var attributes = (DescriptionAttribute[])
fi.GetCustomAttributes(typeof (DescriptionAttribute), false);
return attributes.Length > 0 ?
attributes[0].Description :
enumMember.ToString();
}
然后使用
ReadDescription(RoleType.Guest);
注意:此解决方案假定单一文化应用程序,因为没有特别询问有关多种文化的问题。如果您处于需要处理多种文化的情况,我会使用 DescriptionAttribute
或类似的方法来存储文化感知资源文件的 key 。虽然您可以将枚举成员直接存储在 .resx 文件中,这将创建尽可能紧密的耦合。我看不出您为什么要将应用程序的内部工作(枚举成员名称)与为国际化目的而存在的键值耦合。
关于c# - 将枚举转换为字符串的最佳实践方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2556759/