class AttributeTest
{
public void Test()
{
Type type = typeof(UseAttribute);
object[] customAttributes = type.GetCustomAttributes(true);
foreach (object customAttribute in customAttributes)
{
DefindAttribute defindAttribute = customAttribute as DefindAttribute;
if (defindAttribute != null)
{
Console.WriteLine(defindAttribute.ShowInfo);
}
}
}
}
[Defind("这是第一个特性的创建!")] //是DefindAttribute的特性后面的Attribute就不需要了
class UseAttribute
{
//do nothing;
}
#region 创建特性,要是继承Attribute特性,其实特性也就是一个类
class DefindAttribute :Attribute
{
public DefindAttribute(string showInfo)
{
ShowInfo = showInfo;
}
public string ShowInfo { get; set; }
}
#endregion
在主函数中进行实例化并调用
static void Main(string[] args)
{
AttributeTest attributeTest = new AttributeTest();
attributeTest.Test();
Console.ReadKey();
}