自定义Attribute

[System.AttributeUsage(System.AttributeTargets.Class |  
                       System.AttributeTargets.Struct)  
]  
public class AuthorAttribute : System.Attribute  
{  
    private string name;  
    public double version;  
  
    public AuthorAttribute(string name)  
    {  
        this.name = name;  
        version = 1.0;  
    }  
} 

添加一个Attribute,从System.Attribute继承

使用的地方,在类的定义上面添加

[Author("P. Ackerman", version = 1.1)]  
class SampleClass  
{  
    // P. Ackerman's code goes here...  
}  

以上的代码,可以理解成

Author anonymousAuthorObject = new Author("P. Ackerman");  
anonymousAuthorObject.version = 1.1;  

但是注意这个代码的执行时机,是有人调用了GetCustomAttributes这样的方法,才会导致Attribute构造

如何检查

System.Attribute[] attrs = System.Attribute.GetCustomAttributes(typeof(SampleClass));
        // Displaying output.  
        foreach (System.Attribute attr in attrs)  
        {  
            if (attr is Author)  
            {  
                Author a = (Author)attr;  
                System.Console.WriteLine("   {0}, version {1:f}", a.GetName(), a.version);  
            }  
        }  

 

posted @ 2022-08-16 14:01  内心澎湃的水晶侠  阅读(70)  评论(0编辑  收藏  举报