System.ComponentModel名称空间中提供了很多属性标记在不同场合使用,比如可以使用[Descirpiton]属性对类型、方法或枚举等进行描述。如果系统提供的标记不能满足要求,可以自定义属性,下面是示例代码:
using System;
namespace ZL.NameAttribute
{
[System.AttributeUsage(System.AttributeTargets.All)]
public class MyNameAttribute : System.Attribute
{
private string name;
private string description;
public MyNameAttribute(string name,string description)
{
this.name = name;
this.description = description;
}
public string Name { get { return name; } }
public string Description { get { return description; } }
}
}
使用System.AttributeUsage来规定标记的使用范围。如果希望提取这些属性,可以使用反射方法:
using System.Reflection;
using ZL.NameAttribute;
namespace ZL.GetNameAttribute
{
public class Utility
{
public static void GetAttribute(Type t)
{
MyNameAttribute att;
// Get the class-level attributes.
// Put the instance of the attribute on the class level in the att object.
att = (MyNameAttribute)Attribute.GetCustomAttribute(t, typeof(MyNameAttribute));
if (att != null)
{
Console.WriteLine("The Name Attribute on the class level is: {0}.", att.Name);
Console.WriteLine("The Description Attribute on the class level is: {0}.", att.Description);
}
// Get the method-level attributes.
// Get all methods in this class, and put them
// in an array of System.Reflection.MemberInfo objects.
MemberInfo[] MyMemberInfo = t.GetMethods();
// Loop through all methods in this class that are in the
// MyMemberInfo array.
for (int i = 0; i < MyMemberInfo.Length; i++)
{
att = (MyNameAttribute)Attribute.GetCustomAttribute(MyMemberInfo[i], typeof(MyNameAttribute));
if (att!= null)
{
Console.WriteLine("The Name Attribute for the {0} member is: {1}.",
MyMemberInfo[i].ToString(), att.Name);
Console.WriteLine("The Description Attribute for the {0} member is: {1}.",
MyMemberInfo[i].ToString(), att.Description);
}
}
}
}
}