我知道下面是不可能的,因为枚举的类型必须是int
enum GroupTypes
{
TheGroup = "OEM",
TheOtherGroup = "CMB"
}
从我的数据库中,我得到了一个不全面的代码字段(OEM和CMBs)。我想让这个字段成为一个枚举或其他可以理解的东西。因为如果目标是可读性,解决方案就应该简洁。
我还有其他选择吗?
我知道下面是不可能的,因为枚举的类型必须是int
enum GroupTypes
{
TheGroup = "OEM",
TheOtherGroup = "CMB"
}
从我的数据库中,我得到了一个不全面的代码字段(OEM和CMBs)。我想让这个字段成为一个枚举或其他可以理解的东西。因为如果目标是可读性,解决方案就应该简洁。
我还有其他选择吗?
当前回答
我只需创建一个字典,并使用代码作为键。
编辑:为了解决关于执行反向查找(查找键)的注释,这将不是非常有效。如果有必要,我将编写一个新类来处理它。
其他回答
Glennular Extension方法的一个小调整,所以你可以在其他东西上使用扩展,而不仅仅是ENUM的;
using System;
using System.ComponentModel;
namespace Extensions {
public static class T_Extensions {
/// <summary>
/// Gets the Description Attribute Value
/// </summary>
/// <typeparam name="T">Entity Type</typeparam>
/// <param name="val">Variable</param>
/// <returns>The value of the Description Attribute or an Empty String</returns>
public static string Description<T>(this T t) {
DescriptionAttribute[] attributes = (DescriptionAttribute[])t.GetType().GetField(t.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false);
return attributes.Length > 0 ? attributes[0].Description : string.Empty;
}
}
}
或者使用Linq
using System;
using System.ComponentModel;
using System.Linq;
namespace Extensions {
public static class T_Extensions {
public static string Description<T>(this T t) =>
((DescriptionAttribute[])t
?.GetType()
?.GetField(t?.ToString())
?.GetCustomAttributes(typeof(DescriptionAttribute), false))
?.Select(a => a?.Description)
?.FirstOrDefault()
?? string.Empty;
}
}
这里是扩展方法,我用来获得枚举值作为字符串。首先是枚举。
public enum DatabaseEnvironment
{
[Description("AzamSharpBlogDevDatabase")]
Development = 1,
[Description("AzamSharpBlogQADatabase")]
QualityAssurance = 2,
[Description("AzamSharpBlogTestDatabase")]
Test = 3
}
Description属性来自System.ComponentModel。
这是我的扩展方法:
public static string GetValueAsString(this DatabaseEnvironment environment)
{
// get the field
var field = environment.GetType().GetField(environment.ToString());
var customAttributes = field.GetCustomAttributes(typeof (DescriptionAttribute), false);
if(customAttributes.Length > 0)
{
return (customAttributes[0] as DescriptionAttribute).Description;
}
else
{
return environment.ToString();
}
}
现在,你可以使用下面的代码访问枚举字符串值:
[TestFixture]
public class when_getting_value_of_enum
{
[Test]
public void should_get_the_value_as_string()
{
Assert.AreEqual("AzamSharpBlogTestDatabase",DatabaseEnvironment.Test.GetValueAsString());
}
}
使用类。
编辑:更好的例子
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.");
}
}
为什么不使用相同的枚举,而只是调用.ToString()?
using System;
public class EnumSample
{
enum Holidays
{
Christmas = 1,
Easter = 2
};
public static void Main()
{
Enum myHolidays = Holidays.Christmas;
Console.WriteLine("The value of this instance is '{0}'", myHolidays.ToString());
}
}
基于https://stackoverflow.com/a/1343517/1818723,我提出了一个枚举与TryParse方法
public class FancyStringEnum
{
private FancyStringEnum(string value) { Value = value; }
public string Value { get; private set; }
private static List<FancyStringEnum> choices = new List<FancyStringEnum>
{
new FancyStringEnum("Small") ,
new FancyStringEnum("Big Thing") ,
new FancyStringEnum("Value with Spaces")
};
public static FancyStringEnum Small { get { return choices[0]; } }
public static FancyStringEnum BigThing { get { return choices[1]; } }
public static FancyStringEnum ValueWithSpaces { get { return choices[2]; } }
public override string ToString()
{
return Value;
}
public static bool TryParse(string value, bool ignoreCase, out FancyStringEnum result)
{
var sc = StringComparison.InvariantCulture;
if (ignoreCase)
sc = StringComparison.InvariantCultureIgnoreCase;
foreach (var choice in choices)
{
if (choice.Value.Equals(value, sc))
{
result = choice;
return true;
}
}
result = new FancyStringEnum(null);
return false;
}
public static FancyStringEnum Parse(string value, bool ignoreCase)
{
var sc = StringComparison.InvariantCulture;
if (ignoreCase)
sc = StringComparison.InvariantCultureIgnoreCase;
foreach (var choice in choices)
{
if (choice.Value.Equals(value, sc))
{
return choice;
}
}
return new FancyStringEnum(null);
}
}
传入类型安全的字符串值作为参数:
public static void Do(string message, FancyStringEnum value)
{
if (value == FancyStringEnum.Small)
{
//do something
} else if (value == FancyStringEnum.BigThing)
{
//do something else
}
}
TryParse和Parse在行动:
string something = "something"; //substiture with "small" to see it parsed
if (FancyStringEnum.TryParse(something, true, out var se))
Console.WriteLine(se.Value);
else
Console.WriteLine($"unable to parse {something}");
//or
var v2 = FancyStringEnum.Parse(something, true);
if (v2.Value == null)
Console.WriteLine($"unable to parse {something}");
else
Console.WriteLine(v2.Value); //do something with parsed enum
是否可以提取基类,用更少的代码创建StringEnums