初学Attribute(一个简单实例)
// A simple attribute example
using System;
using System.Reflection;
[AttributeUsage( AttributeTargets.All )]
//指定可以对它们应用特性的应用程序元素。
//可以通过按位“或”运算组合 AttributeTargets 枚举值来获得首选组合。
public class RemarkAttribute : Attribute
//所有特性都从Attribute类继承
{
string pri_remark ; // underlies remark property
public RemarkAttribute( string comment )
{
pri_remark = comment ;
}
public string remark
{
get
{
return pri_remark;
}
}
}
[RemarkAttribute( "This class uses an attribute." )]
//应用自定义特性
class UseAttrib
{
//...
}
class AttribDemo
{
public static void Main()
{
Type t = typeof( UseAttrib );
Console.Write( "Attributes in " + t.Name + ": " );
object[] attribs = t.GetCustomAttributes(false);
//获取所有UseAttrib类的特性
foreach( object o in attribs )
{
Console.WriteLine(o);
}
Console.Write( "Remark: " );
//Retrieve the RemarkAttribute.
Type remarkAttribute = typeof( RemarkAttribute );
RemarkAttribute ra=( RemarkAttribute ) Attribute.GetCustomAttribute( t , remarkAttribute );
//获取RemarkAttribute属性
Console.WriteLine( ra.remark );
Console.Read()
}
}
获取Attributes:
object[] GetCustomAttributes( bool searchBases )
static Attribute GetCustomAttribute( MemberInfo mi,Type attribtype )
最初开始关注特性,是写自定义控件的时候,对那些属性应用的特性,例如
CategoryAttribute
DescriptionAttribute
DefaultValueAttribute
ReadOnlyAttribute
但是特性到底有什么用,这个问题一直困扰着我!除了给一些类以特别的信息之外还有什么用?
posted on 2004-04-07 17:02 polarlm.ne 阅读(1213) 评论(8) 编辑 收藏 举报