using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace TestAttributeDemo
{
    class Class2
    {
        public delegate void TestHandle(string text);//委托一个事件TestHandle

        static void test1_onHandle(string text)//事件出发
        {
            System.Console.WriteLine(text);
        }

        [AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Event)]
        public class Aurtor : Attribute //自定义属性 继承系统的System.Attribute
        {
            public string Name;
            public string Version;
        }
        public class Test  //Test类
        {
            [Aurtor(Name = "test Event1", Version = "1.0.0.4")]
            public event TestHandle onHandle; //定义委托事件onHandle

            public void TestMothe3(int value)
            {
                if (onHandle != null)//如果委托事件不为空
                {
                    onHandle((value+1).ToString());//就加1

                }

            }

        }

        static void Main(string[] args)
        {
            Test test = new Test();//建立类的事例
            Type type = test.GetType();//得到类里所有类型
            test.onHandle += new TestHandle(test1_onHandle);//委托事件onHandle触发事件
            test.TestMothe3(1);//传了一个参数1


            EventInfo[] ets = type.GetEvents();//得到Test类里面所有的事件
            foreach (EventInfo et in ets)
            {
                object[] methodAttributes = et.GetCustomAttributes(false);//得到事件里面的所有属性
                if (methodAttributes != null)
                {
                    foreach (object obj in methodAttributes)
                    {
                        if (obj is Aurtor)//如果属性为Aurtor
                        {
                          Aurtor aurtor = obj as Aurtor;
                          System.Console.WriteLine(aurtor.Name);//输出自定义属性名Name

                        }
                    }
                }
            }
            System.Console.ReadLine();

        }

    }


}

输出:  
        2
        test Event1

posted on 2007-08-22 15:24  萧佰刚  阅读(217)  评论(0编辑  收藏  举报