1. Custom Attribute class: VersionAttribute
[AttributeUsage(AttributeTargets.Class)]
public class VersionAttribute : Attribute
{
public string Name { get; set; }
public string Date { get; set; }
public string Describtion { get; set; }
}
2. Use the Class of the custom Attribute :
[Version(Name = "hyddd", Date = "2009-07-20", Describtion = "hyddd's class")]
public class MyCode
{
//...
}
3. How is the Attribute in the above Class generally used?
class Program
{
static void Main(string[] args)
{
var info = typeof(MyCode);
var classAttribute = (VersionAttribute)Attribute.GetCustomAttribute(info, typeof(VersionAttribute));
Console.WriteLine(classAttribute.Name);
Console.WriteLine(classAttribute.Date);
Console.WriteLine(classAttribute.Describtion);
}
}
3 , 1. Custom Attribute must directly or indirectly inherit System.Attribute .
2. There is a convention here: all custom attribute names should have an Attribute suffix. Because when your Attribute is applied to an element of a program, the compiler first looks for the definition of your Attribute , and if not found, then it looks for the definition of "Attribute Name " + Attribute . If none are found, the compiler reports an error. This is why I can define a VersionAttribute in the first piece of code above , but in the second piece of code, I use the Attribute of Version . :>