定制特性本质上还是一个类,只不过CLR规定定制特性必须继承自Attribute类
定制特性可以应用在类,属性,方法等对象(几乎是元数据中的所有成员)上面
当应用定制特性的时候,是生成了特性的一个实例(按照应用时在特性后面的括号内戴上的命名参数和定位参数),并且将应用的对象和特性关联在一起,这个是体现在文件的元数据中的(编译器会将特性的实例序列化到元数据中)
下面是一个例子,首先定义一个特性类用来表示文本的长度限制,然后定义一个实体类,并且在实体类的属性上应用该特性,最后在运行的时候动态检测实体类实例的所有应用的特性,并且根据特性来检验实体的成员的长度是否超过特性定义的长度。
//特性类
[AttributeUsage(AttributeTargets.All, AllowMultiple=true, Inherited=true)]
public class InputCheckEntityAttribute : Attribute
{
private int m_nMaxLength = 10;
public int MaxLength
{
get { return m_nMaxLength; }
set { m_nMaxLength = value; }
}
}
//实体类
public class EntityToCheck
{
private string m_input = string.Empty;
[InputCheckEntityAttribute(MaxLength = 8)]
public string Input
{
get { return m_input; }
set
{
object[] attrs = this.GetType().GetProperty("Input").GetCustomAttributes(typeof(InputCheckEntityAttribute), true);
foreach(object obj in attrs)
{
Attribute attr = obj as Attribute;
if (attr.GetType().Name == "InputCheckEntityAttribute")
{
int maxLen = (attr as InputCheckEntityAttribute).MaxLength;
if (value.Length > maxLen)
{
throw(new Exception(string.Format("字段Input的最大长度不能超过{0}", maxLen)));
}
}
}
}
}
}
//测试入口函数
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void buttonVal_Click(object sender, EventArgs e)
{
EntityToCheck entity = new EntityToCheck();
entity.Input = txtVal.Text.Trim();
}
}