code1:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyLibrary.AttributeClass
{
[AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = true)]
public class RecordAttribute : Attribute
{
private string recordType; // 记录类型:更新/创建
private string author; // 作者
private DateTime date; // 更新/创建 日期
private string memo; // 备注
// 构造函数,构造函数的参数在特性中也称为“位置参数”。
public RecordAttribute(string recordType, string author, string date)
{
this.recordType = recordType;
this.author = author;
this.date = Convert.ToDateTime(date);
}
// 对于位置参数,通常只提供get访问器
public string RecordType { get { return recordType; } }
public string Author { get { return author; } }
public DateTime Date { get { return date; } }
// 构建一个属性,在特性中也叫“命名参数”
public string Memo
{
get { return memo; }
set { memo = value; }
}
}
[RecordAttribute("modify", "felix", "2010-11-09")]
[RecordAttribute("create", "felix", "2010-11-08")]
public class TestAttribute
{
public string GetInfo() {
return "hello world";
}
public string GetInfos() {
return "hello attribute";
}
}
}
code2:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MyLibrary.AttributeClass;
using System.Reflection;
public partial class AttributePart_AttributeView : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ShowAttributes("TestAttribute");
}
public void ShowAttributes()
{
Type type = typeof(TestAttribute);
object[] records = type.GetCustomAttributes(typeof(RecordAttribute), false);
foreach (RecordAttribute record in records)
{
Response.Write(record);
Response.Write("类型:" + record.RecordType);
Response.Write("作者:" + record.Author);
Response.Write("日期:" + record.Date.ToString());
}
}
public void ShowAttributes(string typeName)
{
Assembly a = Assembly.Load("MyLibrary");
Object obj = a.CreateInstance("MyLibrary.AttributeClass." + typeName);
Type type = obj.GetType();
//get all attributes of TestAttribute
object[] records = type.GetCustomAttributes(typeof(RecordAttribute), false);
foreach (RecordAttribute record in records)
{
Response.Write(record);
Response.Write("类型:" + record.RecordType);
Response.Write("作者:" + record.Author);
Response.Write("日期:" + record.Date.ToString());
}
//get and invoke all methods of TestAttribute
try
{
//MethodInfo[] mi = type.GetMethods();
Response.Write(type.GetMethod("GetInfo").Invoke(obj, null));
Response.Write(type.GetMethod("GetInfos").Invoke(obj, null));
}
catch (Exception ex)
{
Response.Write(ex.Message.ToString());
throw ex;
}
}
}