Skip to content

Instantly share code, notes, and snippets.

@bleis-tift
Forked from cz75hiro/gist:735906
Created December 10, 2010 07:50
Show Gist options
  • Save bleis-tift/735929 to your computer and use it in GitHub Desktop.
Save bleis-tift/735929 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
#pragma warning disable 0414
namespace Enumに柔軟な拡張を追加する試み
{
class Program
{
[RelatedLiterals(typeof(Hoge))]
enum tesyEnum
{
[Obsolete]
a,
b,
}
public static class Hoge
{
static string b = "hoge";
}
[RelatedLiterals(typeof(Piyo))]
enum tesyEnum2
{
c,
d,
e
}
public static class Piyo
{
static int c = 2;
static double d = 0.5;
static MyClass e = new MyClass();
}
public class MyClass { public override string ToString() { return "MyClass"; } }
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.WriteLine(tesyEnum2.e.GetRelatedLiteral());
Console.Read();
}
}
[AttributeUsage(AttributeTargets.Enum, AllowMultiple = false, Inherited = false)]
public class RelatedLiteralsAttribute : Attribute
{
public RelatedLiteralsAttribute(Type t)
{
Type = t;
}
public Type Type { 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)
{
var type = myself.GetType();
try
{
var attr = type.GetCustomAttributes(typeof(RelatedLiteralsAttribute), false).First() as RelatedLiteralsAttribute;
var name = Enum.GetName(type, myself);
var valType = attr.Type;
var f = valType.GetField(name, BindingFlags.NonPublic | BindingFlags.Static);
return f.GetValue(null);
}
catch
{
throw new CustomAttributeFormatException(type.Name + " にEnumAttr属性が指定されていません。");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment