C#Attribute的使用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
class Program
{
    static void Main(string[] args)
    {
        Rectangle r = new Rectangle(4.5, 7.5);
        r.Display();
        Type type = typeof(Rectangle);
        foreach( Object attributes in type.GetCustomAttributes(false))
        {
            DebugInfo dbi = (DebugInfo)attributes;
            if( null != dbi )
            {
                ShowAttributeInfo(dbi);
            }
        }

        foreach( MethodInfo m in type.GetMethods() )
        {
            foreach( Attribute a in m.GetCustomAttributes(true))
            {
                DebugInfo dbi = (DebugInfo)a;
                if( null != dbi )
                {
                    ShowAttributeInfo(dbi);
                }
            }
        }
        Console.ReadLine();
    }

    private static void ShowAttributeInfo( DebugInfo dbi )
    {
        Console.WriteLine("\n================");
        Console.WriteLine("Bug No = {0}", dbi.BugNo);
        Console.WriteLine("Developer = {0}", dbi.Developer);
        Console.WriteLine("LastReview = {0}", dbi.LastReview);
        Console.WriteLine("Msg = {0}", dbi.Message);
    }
}

[DebugInfo(1,"YuXiKuo","11/11/2017", Message = "Return type mismatch")]
[DebugInfo(2,"WangDongGe","10/10/2017", Message = "Unused variable")]
class Rectangle
{
    protected double length;
    protected double width;
    public Rectangle( double l, double w )
    {
        length = l;
        width = w;
    }

    [DebugInfo(3,"YuXiKuo","10/5/2017",Message = "GetArea")]
    public double GetArea()
    {
        return length * width;
    }

    [DebugInfo(4, "YuXiKuo", "10/5/2017", Message = "Display")]
    public void Display()
    {
        Console.WriteLine("Length = {0}", length);
        Console.WriteLine("Width = {0}", width);
        Console.WriteLine("Area = {0}", GetArea());
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值