特性小复习

using ConsoleApplication1;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Status dd = Status.中间;
            string tt = dd.GetEnumAttributeByProperty<Status, TextAttribute>("Text");
        }

    }
    public enum Status
    {
        [Text("Begin", Order = "3")]
        开始 = 1,
        [Text("Middle", Order = "2")]
        中间 = 2,
        [Text("End", Order = "2")]
        结束 = 3
    }

    public class TextAttribute : Attribute
    {
        public string Text { get; set; }

        public string Order { get; set; }
        public TextAttribute(string text)
        {
            this.Text = text;

        }


    }

    public static class Exts
    {
        public static string GetEnumAttributeByProperty<TEnum, TAttr>(this TEnum enums, string property) where TAttr : Attribute
        {
            if (!typeof(TEnum).IsEnum)
                return "";
            var type = enums.GetType();
            var d1 = Enum.GetName(typeof(TEnum), enums);
            var field = type.GetField(d1);
            var descAttr = Attribute.GetCustomAttribute(field, typeof(TAttr));
            var property1 = descAttr.GetType().GetProperty(property);
            var t = property1.GetValue(descAttr);


            var name = type.GetEnumName(enums);

     
            return t.ToString();



        }
    }
}

 

posted @ 2021-12-28 11:12  安以痕_陈  阅读(25)  评论(0编辑  收藏  举报