1. 程式人生 > 其它 >C#中的Attribute二

C#中的Attribute二

一、定義特性

//欄位屬性約束,在定的的特性上使用系統特性
    [AttributeUsage(AttributeTargets.All,AllowMultiple =true,Inherited =true)]
   public class ShowAttribute:Attribute
    {   
        public string ShowInfo { get; set; }
        public void Show()
        {
            Console.WriteLine(ShowInfo);
        }
    }

二、使用特性

 [Show(ShowInfo = "我是在類上的第一個特性")]
    [Show(ShowInfo = "我是在類上的第二個特性")]
    public class ShowTest
    {

        [Show(ShowInfo = "我是在方法上的特性")]//通過特性類的屬性進行傳入值
        public void TestMethod()
        {

        }

        [Show(ShowInfo = "我是在屬性上的特性")]
        public string TestProperty { get; set; }

        [Show(ShowInfo = "我是在欄位上的特性")]
        public string TestFiled;
    }

三、呼叫特性實現

   public static class InvokeCenter
    {

        //此處使用的是拓展方法
        public static void InvokeManager<T>( this T showTest) where T:new()//泛型無參構造約束
        {
            Type type = showTest.GetType();
            if (type.IsDefined(typeof(ShowAttribute),true))
            {
                //在類上面查詢特性
                object[] attributes=type.GetCustomAttributes(typeof(ShowAttribute), true);
                foreach (ShowAttribute attribute in attributes)
                {
                    attribute.Show();
                }

                //在方法上查詢
                foreach (MethodInfo method in type.GetMethods())
                {
                    if (method.IsDefined(typeof(ShowAttribute), true))
                    {
                        object[] attributeMethods = method.GetCustomAttributes(typeof(ShowAttribute), true);
                        foreach (ShowAttribute attribute in attributeMethods)
                        {
                            attribute.Show();
                        }
                    }
                }

                //在屬性上查詢
                foreach (PropertyInfo property in type.GetProperties())
                {
                    if (property.IsDefined(typeof(ShowAttribute), true))
                    {
                        object[] attributeProperty = property.GetCustomAttributes(typeof(ShowAttribute), true);
                        foreach (ShowAttribute attribute in attributeProperty)
                        {
                            attribute.Show();
                        }
                    }
                }

                //在欄位上查詢
                foreach (FieldInfo field in type.GetFields())
                {
                    if (field.IsDefined(typeof(ShowAttribute), true))
                    {
                        object[] attributeField = field.GetCustomAttributes(typeof(ShowAttribute), true);
                        foreach (ShowAttribute attribute in attributeField)
                        {
                            attribute.Show();
                        }
                    }
                }


            }
        }

    }

四、呼叫測試

通過拓展方法呼叫

 ShowTest showTest = new ShowTest();
 showTest.InvokeManager();