关联枚举在C#中的字符串 [英] Associating enums with strings in C#
本文介绍了关联枚举在C#中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道下面是不可能的,因为它必须是一个int
I know the following is not possible because it has to be an int
enum GroupTypes
{
TheGroup = "OEM",
TheOtherGroup = "CMB"
}
这是我的数据库我得到科钦prehensive codeS(贴牌和招商银行的)的字段。我想使这个领域成为一个枚举或别的东西可以理解的。因为目标是可读性的解决办法应该是简洁。
我有什么其他选择?
From my database I get a field with incomprehensive codes (the OEM and CMB's). I would want to make this field into an enum or something else understandable. Because the target is readability the solution should be terse.
What other options do I have?
推荐答案
我喜欢的一类,而不是使用方法的属性,因为它们看起来更枚举等。
I like to use properties in a class instead of methods, since they look more enum-like.
下面是一个记录器一个例子:
Here's a example for a Logger:
public class LogCategory
{
private LogCategory(string value) { Value = value; }
public string Value { get; set; }
public static LogCategory Trace { get { return new LogCategory("Trace"); } }
public static LogCategory Debug { get { return new LogCategory("Debug"); } }
public static LogCategory Info { get { return new LogCategory("Info"); } }
public static LogCategory Warning { get { return new LogCategory("Warning"); } }
public static LogCategory Error { get { return new LogCategory("Error"); } }
}
传入类型安全的字符串值作为一个参数:
public static void Write(string message, LogCategory logCategory)
{
var log = new LogEntry { Message = message };
Logger.Write(log, logCategory.Value);
}
用法:
Logger.Write("This is almost like an enum.", LogCategory.Info);
这篇关于关联枚举在C#中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文