質問
.NetでEnum型を操作するためのオープンソースライブラリまたはサンプルを探しています。人々がEnumに使用する標準の拡張機能(TypeParseなど)に加えて、特定の列挙値のDescription属性の値を返す、またはDescription属性値を持つ列挙値を返すなどの操作を実行する方法が必要です。指定された文字列に一致します。
例:
//if extension method
var race = Race.FromDescription("AA") // returns Race.AfricanAmerican
//and
string raceDescription = Race.AfricanAmerican.GetDescription() //returns "AA"
解決
まだ存在しない場合は、開始してください! Stackoverflowの他の回答から必要なすべてのメソッドを見つけることができます-それらを1つのプロジェクトにロールアップするだけです。始めるためのいくつかを以下に示します。
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;
}
}
他のヒント
先日、列挙型の代わりにクラスを使用することに関するこのブログ投稿を読みました:
http://www.lostechies .com / blogs / jimmy_bogard / archive / 2008/08/12 / enumeration-classes.aspx
enumクラスの基礎として機能する抽象クラスの使用を提案します。基本クラスには、等式、解析、比較などがあります。
これを使用すると、次のような列挙型のクラスを作成できます(記事の例):
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) { }
}
所属していません StackOverflow