你啥都没干,怎会执行呢,给你个连接学习一下
http://www.cnblogs.com/dc10101/archive/2009/03/24/1420199.html

解决方案 »

  1.   

    @bdmh
    怎么没执行呢,Main执行了静态方法AddUser,那个特性是附加在AddUser方法上的?难道特性在它附加的对象上当被附加对象执行时特性本身不会执行么?
      

  2.   

    哥attribute只是用来标注的,其它方式要来使用该方法,字段,属性时,会检查它们头上是否有这些标注属性,从来确定接下来怎么使用它们。至于自定义attribute,要执行本身的构造函数,只有你去实例化它才行:       static void Main(string[] args)
            {
                UserService.AddUser();            Type classType = typeof(UserService);            foreach (MethodInfo method in classType.GetMethods())
                {
                    foreach (Attribute attr in Attribute.GetCustomAttributes(method))
                    {
                        if (attr.GetType() == typeof(MyAttribute))
                        {
                            MyAttribute att = (MyAttribute)attr;
                        }
                    }
                }
            }        class UserService
            {
                [My]
                public static void AddUser()
                {
                    Console.WriteLine("数据写入到数据库成功!");
                }
            }        [AttributeUsage(AttributeTargets.All)]
            class MyAttribute : System.Attribute
            {
                public MyAttribute()
                {
                    Console.WriteLine("=============================");
                    Console.WriteLine("时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    Console.WriteLine("=============================");
                }
            }
      

  3.   

    感觉你这样写的有点奇怪,我记得Attribute好像就是一个类,你为何还要在外面给它多加个类UserService,你试下
        class Program
        {
            static void Main(string[] args)
            {
                AddUser();
            }
            [My]
            public static void AddUser()
            {
                Console.WriteLine("数据写入到数据库成功!");
            }
            class MyAttribute : System.Attribute
            {
                public MyAttribute()
                {
                    Console.WriteLine("=============================");
                    Console.WriteLine("时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                    Console.WriteLine("=============================");
                }
            }
        }
    看行不行