Skip to content

Instantly share code, notes, and snippets.

@cz75hiro
Created December 10, 2010 07:25
Show Gist options
  • Save cz75hiro/735906 to your computer and use it in GitHub Desktop.
Save cz75hiro/735906 to your computer and use it in GitHub Desktop.
Enumに柔軟な拡張を追加する試み
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace Enumに柔軟な拡張を追加する試み {
class Program {
enum tesyEnum {
[Obsolete]
a,
[RelatedLiteral("hoge")]
b,
}
enum tesyEnum2 {
[RelatedLiteral(2)]
c,
[RelatedLiteral(0.5)]
d
}
static void Main(string[] args) {
//Console.WriteLine(tesyEnum.a.GetRelatedLiteral()); RelatedLiteral属性つけてないと例外発生
Console.WriteLine(tesyEnum.b.GetRelatedLiteral());
Console.WriteLine(tesyEnum2.c.GetRelatedLiteral());
Console.WriteLine(tesyEnum2.d.GetRelatedLiteral());
Console.Read();
}
}
[AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inherited = false)]
public class RelatedLiteralAttribute : Attribute {
public RelatedLiteralAttribute(object value) {
Value = value;
}
public dynamic Value { get; private set; }
}
/// <summary>
/// enum拡張メソッド用クラス
/// </summary>
public static class EnumExtension {
/// <summary>
/// RelatedLiteral属性に指定したリテラルを取得します。
/// </summary>
/// <param name="myself"></param>
/// <returns></returns>
public static dynamic GetRelatedLiteral(this Enum myself) {
Type type = myself.GetType();
string name = Enum.GetName(type, myself);
try {
FieldInfo fi = type.GetField(name);
var items = (RelatedLiteralAttribute[])fi.GetCustomAttributes(typeof(RelatedLiteralAttribute), false);
return items[0].Value;
}
catch (IndexOutOfRangeException e) {
throw new CustomAttributeFormatException(type.Name + " の " + name + " 要素にEnumAttr属性が指定されていません。");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment