我知道下面是不可能的,因为枚举的类型必须是int
enum GroupTypes
{
TheGroup = "OEM",
TheOtherGroup = "CMB"
}
从我的数据库中,我得到了一个不全面的代码字段(OEM和CMBs)。我想让这个字段成为一个枚举或其他可以理解的东西。因为如果目标是可读性,解决方案就应该简洁。
我还有其他选择吗?
我知道下面是不可能的,因为枚举的类型必须是int
enum GroupTypes
{
TheGroup = "OEM",
TheOtherGroup = "CMB"
}
从我的数据库中,我得到了一个不全面的代码字段(OEM和CMBs)。我想让这个字段成为一个枚举或其他可以理解的东西。因为如果目标是可读性,解决方案就应该简洁。
我还有其他选择吗?
当前回答
另一种处理这个问题的方法是,有一个枚举和一个字符串数组,将枚举值映射到字符串列表:
public enum GroupTypes
{
TheGroup = 0,
TheOtherGroup
}
string[] GroupTypesStr = {
"OEM",
"CMB"
};
你可以这样使用它:
Log.Write(GroupTypesStr[(int)GroupTypes.TheOtherGroup]);
它将提示CMB
优点:
简单干净的代码。 高性能(特别是与那些方法相比 使用类)
缺点:
易于混乱的列表时,编辑它,但这将是一个好的 短名单。
其他回答
我只需创建一个字典,并使用代码作为键。
编辑:为了解决关于执行反向查找(查找键)的注释,这将不是非常有效。如果有必要,我将编写一个新类来处理它。
您是否考虑过使用字典查找表?
enum GroupTypes
{
TheGroup,
TheOtherGroup
}
Dictionary<string, GroupTypes> GroupTypeLookup = new Dictionary<string, GroupTypes>();
// initialize lookup table:
GroupTypeLookup.Add("OEM", TheGroup);
GroupTypeLookup.Add("CMB", TheOtherGroup);
然后,您可以使用GroupTypeLookup.TryGetValue()在读取字符串时查找它。
在VS 2015中,你可以使用nameof
public class LogCategory
{
public static string Trace;
public static string Debug;
public static string Info;
public static string Warning;
public static string Error;
}
用法:
Logger.Write("This is almost like an enum.", nameof(LogCategory.Info));
c#不支持枚举字符串,但在大多数情况下,您可以使用List或Dictionary来获得所需的效果。
打印通过/失败结果:
List<string> PassFail = new List<string> { "FAIL", "PASS" };
bool result = true;
Console.WriteLine("Test1: " + PassFail[result.GetHashCode()]);
我不需要任何健壮的东西,比如将字符串存储在属性中。我只需要转动MyEnum之类的东西。BillEveryWeek变成“每周账单”或MyEnum。将elegacysystem转换为“使用遗留系统”——基本上通过驼峰式大小写将枚举拆分为单个小写单词。
public static string UnCamelCase(this Enum input, string delimiter = " ", bool preserveCasing = false)
{
var characters = input.ToString().Select((x, i) =>
{
if (i > 0 && char.IsUpper(x))
{
return delimiter + x.ToString(CultureInfo.InvariantCulture);
}
return x.ToString(CultureInfo.InvariantCulture);
});
var result = preserveCasing
? string.Concat(characters)
: string.Concat(characters).ToLower();
var lastComma = result.LastIndexOf(", ", StringComparison.Ordinal);
if (lastComma > -1)
{
result = result.Remove(lastComma, 2).Insert(lastComma, " and ");
}
return result;
}
myenume . uselegacysystem . uncamelcase()输出"使用遗留系统"
如果设置了多个标志,它会将其转换为普通英语(逗号分隔,除了最后一个逗号中的“and”)。
var myCustomerBehaviour = MyEnum.BillEveryWeek | MyEnum.UseLegacySystem | MyEnum.ChargeTaxes;
Console.WriteLine(myCustomerBehaviour.UnCamelCase());
//outputs "bill every week, use legacy system and charge taxes"