代码改变世界

关于C# 自定义Attribute 的例子 - Demo2

2011-07-03 00:34  音乐让我说  阅读(287)  评论(0编辑  收藏  举报

直接贴代码了:

using System;
using System.Reflection;

namespace ConAppAttribute
{
    class Program
    {
        static void Main(string[] args)
        {
            UserService.AddUser();
            Type type = typeof(UserService);
            MethodInfo mi = type.GetMethod("AddUser");
            Console.WriteLine("\n第一种方式来反射:");
            MyLogAttribute attrsObj = (MyLogAttribute)mi.GetCustomAttributes(typeof(MyLogAttribute), false)[0];
            attrsObj.WriteLog();
            Console.WriteLine("\n第二种方式来反射:");
            MyLogAttribute attrsObj2 = (MyLogAttribute)Attribute.GetCustomAttribute(mi, typeof(MyLogAttribute));
            attrsObj2.WriteLog();
            Console.ReadKey();
        }
    }

    class UserService
    {
        [MyLog("添加用户")]
        public static void AddUser()
        {
            Console.WriteLine("数据写入到数据库成功!");
        }

        [MyLog("删除用户")]
        public static void DeleteUser()
        {
            Console.WriteLine("数据从数据库中删除成功!");
        }
    }

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
    class MyLogAttribute : System.Attribute
    {
        public MyLogAttribute(string logMessage)
        {
            this.LogMessage = logMessage;
        }

        public string LogMessage
        {
            get;
            set;
        }

        public void WriteLog()
        {
            Console.WriteLine("=============================");
            Console.WriteLine("时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            Console.WriteLine("日志消息:" + LogMessage);
            Console.WriteLine("=============================");
        }
    }
}

运行结果:

谢谢浏览!