.net 枚举实用程序库
我正在寻找一个开源库或在.Net中使用枚举类型的示例。除了人们用于枚举的标准扩展(TypeParse等),我还需要一种执行操作的方法,如返回给定枚举值的Description属性值,或返回具有与给定字符串匹配的Description属性值的枚举值 例如:.net 枚举实用程序库,.net,enums,enumeration,.net,Enums,Enumeration,我正在寻找一个开源库或在.Net中使用枚举类型的示例。除了人们用于枚举的标准扩展(TypeParse等),我还需要一种执行操作的方法,如返回给定枚举值的Description属性值,或返回具有与给定字符串匹配的Description属性值的枚举值 例如: //if extension method var race = Race.FromDescription("AA") // returns Race.AfricanAmerican //and string raceDescription =
//if extension method
var race = Race.FromDescription("AA") // returns Race.AfricanAmerican
//and
string raceDescription = Race.AfricanAmerican.GetDescription() //returns "AA"
如果还没有,那就开始吧!您可能可以从Stackoverflow上的其他答案中找到所需的所有方法—只需将它们放在一个项目中即可。以下是一些让您开始学习的方法:
公共静态类枚举
{
公共静态可空解析(字符串输入),其中T:struct
{
//因为我们不能做泛型类型约束
if(!typeof(T).IsEnum)
{
抛出新ArgumentException(“泛型类型“T”必须是枚举”);
}
如果(!string.IsNullOrEmpty(输入))
{
if(Enum.GetNames(typeof(T)).Any(
e=>e.Trim().ToUpperInvariant()==input.Trim().ToUpperInvariant())
{
返回(T)Enum.Parse(typeof(T),输入,true);
}
}
返回null;
}
}
前几天我读了这篇关于使用类而不是枚举的博文:
建议使用抽象类作为枚举类的基础。基类具有相等、解析、比较等功能
使用它,您可以为您的枚举创建如下类(摘自本文的示例):
谢谢你的俏皮话。本文提出了一些与我的情况相关的非常好的观点。还有Jon Skeet的泛型枚举类型约束库:第一部分是的副本。
public static string GetDescription(this Enum value)
{
FieldInfo field = value.GetType().GetField(value.ToString());
object[] attribs = field.GetCustomAttributes(typeof(DescriptionAttribute), true));
if(attribs.Length > 0)
{
return ((DescriptionAttribute)attribs[0]).Description;
}
return string.Empty;
}
public static class EnumUtils
{
public static Nullable<T> Parse<T>(string input) where T : struct
{
//since we cant do a generic type constraint
if (!typeof(T).IsEnum)
{
throw new ArgumentException("Generic Type 'T' must be an Enum");
}
if (!string.IsNullOrEmpty(input))
{
if (Enum.GetNames(typeof(T)).Any(
e => e.Trim().ToUpperInvariant() == input.Trim().ToUpperInvariant()))
{
return (T)Enum.Parse(typeof(T), input, true);
}
}
return null;
}
}
public class EmployeeType : Enumeration
{
public static readonly EmployeeType Manager
= new EmployeeType(0, "Manager");
public static readonly EmployeeType Servant
= new EmployeeType(1, "Servant");
public static readonly EmployeeType AssistantToTheRegionalManager
= new EmployeeType(2, "Assistant to the Regional Manager");
private EmployeeType() { }
private EmployeeType(int value, string displayName) : base(value, displayName) { }
}