关于C# 自定义Attribute 的例子 - Demo2
2011-07-03 00:34 音乐让我说 阅读(293) 评论(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("=============================");
        }
    }
}
运行结果:

谢谢浏览!
    作者:音乐让我说(音乐让我说 - 博客园)
    
    出处:http://music.cnblogs.com/
    文章版权归本人所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号