首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

问个Attribute的小疑点?

2014-01-17 
问个Attribute的小问题???????????????namespace ConsoleApplication1{class Program{static void Main(st

问个Attribute的小问题???????????????


namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            UserService.AddUser();
        }
    }
    class UserService
    {
        [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("=============================");
        }
    }
}


为什么自定义的特性的构造函数内的代码没执行???求科普,求指点???
[解决办法]
你啥都没干,怎会执行呢,给你个连接学习一下
http://www.cnblogs.com/dc10101/archive/2009/03/24/1420199.html
[解决办法]
当你检索特性的时候它才构造一个特性实例,这时构造函数才执行,否则它只是元数据的一部分
[解决办法]
特性当然不会被执行。它只是打标记。
你根本对特性能做什么都误解了。
[解决办法]
哥。。。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("=============================");
            }
        }

热点排行