zoukankan      html  css  js  c++  java
  • 自定义属性与事件委托相结合的实例

    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

  • 相关阅读:
    HDU 2888 Check Corners (模板题)【二维RMQ】
    POJ 3264 Balanced Lineup(模板题)【RMQ】
    poj 3368 Frequent values(经典)【RMQ】
    SPOJ RPLN (模板题)(ST算法)【RMQ】
    UVA 796 Critical Links(模板题)(无向图求桥)
    UVA 315 Network (模板题)(无向图求割点)
    POJ 2029 Get Many Persimmon Trees (模板题)【二维树状数组】
    poj 3067 Japan 【树状数组】
    POJ 2481 Cows 【树状数组】
    POJ 1195 Mobile phones【二维树状数组】
  • 原文地址:https://www.cnblogs.com/xiaobaigang/p/865473.html
Copyright © 2011-2022 走看看