Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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属性が指定されていません。");
- }
- }
- }
- }
Add Comment
Please, Sign In to add comment