我有这样的枚举:
public enum ObectTypes
{
TypeOne,
TypeTwo,
TypeThree,
...
TypeTwenty
}
Run Code Online (Sandbox Code Playgroud)
然后我需要将此枚举转换为字符串.现在我这样做:
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;
}
Run Code Online (Sandbox Code Playgroud)
我很确定有更好的方法可以做到这一点,我正在寻找一些良好的实践解决方案.
编辑:结果字符串中没有一个模式.
提前致谢.
Chr*_*sic 19
我使用了[Description]来自的属性System.ComponentModel
例:
public enum RoleType
{
[Description("Allows access to public information")] Guest = 0,
[Description("Allows access to the blog")] BlogReader = 4,
}
Run Code Online (Sandbox Code Playgroud)
然后从中读取我的意思
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();
}
Run Code Online (Sandbox Code Playgroud)
然后使用
ReadDescription(RoleType.Guest);
注意:此解决方案假设单个文化应用程序,因为没有特别询问有关多种文化的内容 如果您处于需要处理多种文化的情况,我会使用DescriptionAttribute或类似的方法将密钥存储到文化感知资源文件中.虽然您可以将枚举成员直接存储在.resx文件中,该文件可以创建最紧密的耦合.我认为没有理由要将应用程序的内部工作(枚举成员名称)与为国际化目的而存在的键值相结合.
如果您需要自定义字符串,最好的选择是创建Dictionary< ObjectTypes, string>一个字典查找.
如果您对默认的ToString()功能没问题,只需使用即可 typeObj.ToString();
对于字典方法,您可以:
private static Dictionary<ObjectTypes, string> enumLookup;
static MyClass()
{
enumLookup = new Dictionary<ObjectTypes, string>();
enumLookup.Add(ObjectTypes.TypeOne, "This is type T123");
enumLookup.Add(ObjectTypes.TypeTwo, "This is type T234");
// enumLookup.Add...
}
Run Code Online (Sandbox Code Playgroud)
你的方法变成:
public string ConvertToCustomTypeName(ObjectTypes typeObj)
{
// Shouldn't need TryGetValue, unless you're expecting people to mess with your enum values...
return enumLookup[typeObj];
}
Run Code Online (Sandbox Code Playgroud)