Attribute特性,可以往程序集中写入一些元数据。微软类库中自带很多 Attribute类,某些时候,需要对类标注一下 Attribute。那么自定义 Attribute的用处是什么的,或者说,什么时候我们需要自定义 Attribute。
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Dynamic;
namespace ConsoleApplication1
{
class Program
{
// create custom attribute to be assigned to class members
[AttributeUsage(AttributeTargets.Class |
AttributeTargets.Constructor |
AttributeTargets.Field |
AttributeTargets.Method |
AttributeTargets.Property,
AllowMultiple = true)]
public class BugFixAttribute : System.Attribute
{
// attribute constructor for positional parameters
public BugFixAttribute
(
int bugID,
string programmer,
string date
)
{
this.BugID = bugID;
this.Programmer = programmer;
this.Date = date;
}
// accessors
public int BugID { get; private set; }
public string Date { get; private set; }
public string Programmer { get; private set; }
// property for named parameter
public string Comment { get; set; }
}
// ********* assign the attributes to the class ********
[BugFixAttribute(121, "Jesse Liberty", "01/03/08")]
[BugFixAttribute(107, "Jesse Liberty", "01/04/08",
Comment = "Fixed off by one errors")]
public class MyMath
{
public double DoFunc1(double param1)
{
return param1 + DoFunc2(param1);
}
public double DoFunc2(double param1)
{
return param1 / 3;
}
}
public class Tester
{
static void Main(string[] args)
{
MyMath mm = new MyMath();
Console.WriteLine("Calling DoFunc(7). Result: {0}",
mm.DoFunc1(7));
// get the member information and use it to
// retrieve the custom attributes
System.Reflection.MemberInfo inf = typeof(MyMath);
object[] attributes;
attributes = inf.GetCustomAttributes(
typeof(BugFixAttribute), false);
// iterate through the attributes, retrieving the
// properties
foreach (Object attribute in attributes)
{
BugFixAttribute bfa = (BugFixAttribute)attribute;
Console.WriteLine("\nBugID: {0}", bfa.BugID);
Console.WriteLine("Programmer: {0}", bfa.Programmer);
Console.WriteLine("Date: {0}", bfa.Date);
Console.WriteLine("Comment: {0}", bfa.Comment);
}
}
}
}
}