我知道以下是不可能的,因为枚举类型必须是int。
enum GroupTypes
{
TheGroup = "OEM",
TheOtherGroup = "CMB"
}
我从数据库中获取了一个包含难以理解的代码(OEM
和CMB
)的字段。 我想将此字段转换为枚举
或其他易于理解的形式。 因为如果目标是可读性,解决方案应该是简洁的。
我还有哪些选项?
我知道以下是不可能的,因为枚举类型必须是int。
enum GroupTypes
{
TheGroup = "OEM",
TheOtherGroup = "CMB"
}
我从数据库中获取了一个包含难以理解的代码(OEM
和CMB
)的字段。 我想将此字段转换为枚举
或其他易于理解的形式。 因为如果目标是可读性,解决方案应该是简洁的。
我还有哪些选项?
public class LogCategory
{
private LogCategory(string value) { Value = value; }
public string Value { get; private 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 override string ToString()
{
return Value;
}
}
将类型安全的字符串值作为参数传入:
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);
ToString
方法以返回Value
。然后提供了隐式转换操作符来实现字符串与该类型之间的互相转换。其中包括从该类型到字符串的转换:public static implicit operator String(LogCategory category) { return Value; }
。 - ZarephethValue
的赋值方法设为私有的,然而。 - bohdan_trotsenkopublic static string Trace => "Trace";
。 - JonathanPeelpublic enum MyEnum
{
[Description("String 1")]
V1= 1,
[Description("String 2")]
V2= 2
}
你的扩展类
public static class MyEnumExtensions
{
public static string ToDescriptionString(this MyEnum val)
{
DescriptionAttribute[] attributes = (DescriptionAttribute[])val
.GetType()
.GetField(val.ToString())
.GetCustomAttributes(typeof(DescriptionAttribute), false);
return attributes.Length > 0 ? attributes[0].Description : string.Empty;
}
}
使用方法:
MyEnum myLocal = MyEnum.V1;
print(myLocal.ToDescriptionString());
.ToString()
已经使用了反射,因此您不会因使用这种方法而丢失任何内容,并且还能提高可读性。 - James Kingpublic static string ToDescriptionString(this Enum ...
即可,无需显式键入为 MyEnum
。 - LeeCamblSystem.ComponentModel;
。 - Cody G使用一个带有常量的静态类如何?
static class GroupTypes
{
public const string TheGroup = "OEM";
public const string TheOtherGroup = "CMB";
}
void DoSomething(string groupType)
{
if(groupType == GroupTypes.TheGroup)
{
// Be nice
}
else if (groupType == GroupTypes.TheOtherGroup)
{
// Continue to be nice
}
else
{
// unexpected, throw exception?
}
}
GroupTypes
作为参数类型传递,因为它是一个静态类。这就是 Even Mien 的回答要解决的问题。在这种情况下,你需要使用 void DoSomething(string groupType)
,这意味着 groupType
可以具有任何字符串值,甚至是你没有预期到的值,这意味着你必须准备好处理那些无效的类型,并决定如何处理它们(例如通过抛出异常)。Even Mien 的答案通过将有效输入的数量限制为由 LogCategory
类定义的选项来解决这个问题。 - Pharap我采用了之前回答中提到的结构,但取消了任何复杂性。 对我来说,这最像创建字符串枚举。 它的使用方式与枚举的使用方式相同。
struct ViewTypes
{
public const string View1 = "Whatever string you like";
public const string View2 = "another string";
}
使用示例:
switch( some_string_variable )
{
case ViewTypes.View1: /* do something */ break;
case ViewTypes.View2: /* do something else */ break;
}
尝试将常量添加到静态类中。这样你不会得到一个类型,但是你会拥有可读性强、组织良好的常量:
public static class GroupTypes {
public const string TheGroup = "OEM";
public const string TheOtherGroup = "CMB";
}
实际上你可以很容易地完成它。使用以下代码。
enum GroupTypes
{
OEM,
CMB
};
如果你想获取每个枚举元素的字符串值,只需使用以下代码行。
String oemString = Enum.GetName(typeof(GroupTypes), GroupTypes.OEM);
我过去已经成功地使用了这种方法,也使用常量类来保存字符串常量,两种方法都行得不错。但我更倾向于使用这种方法。
some string. 123
是行不通的。 - phuclv您可以为枚举中的项目添加属性,然后使用反射从属性中获取值。
您需要使用“field”说明符来应用属性,如下所示:
enum GroupTypes
{
[field:Description("OEM")]
TheGroup,
[field:Description("CMB")]
TheOtherGroup
}
然后,您需要反射枚举类型(在此示例中为GroupTypes)的静态字段,并使用反射获取您正在查找的值的DescriptionAttribute
:
public static DescriptionAttribute GetEnumDescriptionAttribute<T>(
this T value) where T : struct
{
// The type of the enum, it will be reused.
Type type = typeof(T);
// If T is not an enum, get out.
if (!type.IsEnum)
throw new InvalidOperationException(
"The type parameter T must be an enum type.");
// If the value isn't defined throw an exception.
if (!Enum.IsDefined(type, value))
throw new InvalidEnumArgumentException(
"value", Convert.ToInt32(value), type);
// Get the static field for the value.
FieldInfo fi = type.GetField(value.ToString(),
BindingFlags.Static | BindingFlags.Public);
// Get the description attribute, if there is one.
return fi.GetCustomAttributes(typeof(DescriptionAttribute), true).
Cast<DescriptionAttribute>().SingleOrDefault();
}
我选择返回DescriptionAttribute
本身,以便您可以确定是否应用了该属性。
使用一个类。
编辑:更好的示例
class StarshipType
{
private string _Name;
private static List<StarshipType> _StarshipTypes = new List<StarshipType>();
public static readonly StarshipType Ultralight = new StarshipType("Ultralight");
public static readonly StarshipType Light = new StarshipType("Light");
public static readonly StarshipType Mediumweight = new StarshipType("Mediumweight");
public static readonly StarshipType Heavy = new StarshipType("Heavy");
public static readonly StarshipType Superheavy = new StarshipType("Superheavy");
public string Name
{
get { return _Name; }
private set { _Name = value; }
}
public static IList<StarshipType> StarshipTypes
{
get { return _StarshipTypes; }
}
private StarshipType(string name, int systemRatio)
{
Name = name;
_StarshipTypes.Add(this);
}
public static StarshipType Parse(string toParse)
{
foreach (StarshipType s in StarshipTypes)
{
if (toParse == s.Name)
return s;
}
throw new FormatException("Could not parse string.");
}
}
enum DBGroupTypes
{
OEM = 0,
CMB = 1
}
现在,您可以使用Enum.Parse从字符串“OEM”和“CMB”中检索正确的DBGroupTypes值。然后,您可以将它们转换为int,并从想要在模型中进一步使用的正确枚举中检索正确的值。
另一种处理这个问题的方法是创建一个枚举和一个字符串数组,将枚举值映射到字符串列表中:
public enum GroupTypes
{
TheGroup = 0,
TheOtherGroup
}
string[] GroupTypesStr = {
"OEM",
"CMB"
};
你可以像这样使用它:
Log.Write(GroupTypesStr[(int)GroupTypes.TheOtherGroup]);
它会提示招商银行
优点:
缺点: