您的位置:首页 > 编程语言 > C#

C#Attribute的使用

2017-01-11 00:08 489 查看
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());
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: