對類別裡的方法定義自訂屬性(Attribute)

  • 833
  • 0
  • c#
  • 2016-05-18

摘要:自訂屬性

namespace GetCurrentMethodTest
{
    [System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Struct|System.AttributeTargets.Method)]  //指定屬性可使用於 class、struct、method
    public class PhoneFunctiion : System.Attribute
    {
        public bool isPhoneFunctiion;

        public PhoneFunctiion(bool isPhoneFunctiion)
        {
            this.isPhoneFunctiion = isPhoneFunctiion;
        }
    }

    //[PhoneFunctiion(true)]
    class SampleClass
    {
        [PhoneFunctiion(true)]
        public void aaaa()
        {
        }
    }
}
using System;
using System.Reflection;

namespace AttributesSample
{
    class Program
    {
        static void Main(string[] args)
        {
            MyClass mc = new MyClass();
        }
    }

    /// 
/// 自訂屬性 ///

[AttributeUsage(AttributeTargets.Method)] internal class MyAttribute : Attribute { internal string text; internal MyAttribute(string text) { this.text = text; } } public class MyClass { [MyAttribute("Hello Method")] public void MyMethod() { } public void MyMethod2() { } internal MyClass() { Attribute[] attributes; MethodInfo[] mis = this.GetType().GetMethods(); //取出這個class的所有method foreach (MethodInfo mi in mis) { attributes = Attribute.GetCustomAttributes(mi); //取出所有method的自訂屬性 foreach (Attribute aa in attributes) { MyAttribute ma = aa as MyAttribute; //轉換自訂屬性為MyAttribute if (ma == null) continue; //屬性不是MyAttribute,轉換失敗 Console.WriteLine(ma.text); //輸出屬性值 } } } } }