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

直接贴代码了:

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("=============================");
        }
    }
}

运行结果:

2011070300330786.jpg

谢谢浏览!

转载于:https://www.cnblogs.com/Music/archive/2011/07/03/c-sharp-customer-attribute-demo2.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值