Csharp/CSharp Tutorial/Reflection/Attributes
Get Custom Attributes
<source lang="csharp">using System; using System.Reflection; class Program {
static void Main(string[] args) { string assemblyName = "Your"; try { Assembly a = Assembly.LoadFrom(assemblyName); object[] attributes = a.GetCustomAttributes(true); if (attributes.Length > 0) { Console.WriteLine("Assembly attributes for "{0}"...", assemblyName); foreach (object o in attributes) Console.WriteLine(" {0}", o.ToString()); } else Console.WriteLine("Assembly {0} contains no Attributes.", assemblyName); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } }
}</source>
Using Reflection to get Custom Attributes
<source lang="csharp">using System; using System.Collections.Generic; using System.Text;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = true)] public class BugFixAttribute : System.Attribute { public BugFixAttribute(int bugID,string programmer,string date){ this.BugID = bugID; this.Programmer = programmer; this.Date = date; } public int BugID; public string Date; public string Programmer; public string Comment { get; set; } } [BugFixAttribute(1, "A", "01/04/05",Comment = "value")] public class MyMath{ public double DoFunc1(double param1) { return param1 + DoFunc2(param1); } public double DoFunc2(double param1) { return param1 / 3; } } public class Tester { public static void Main() { MyMath mm = new MyMath(); System.Reflection.MemberInfo inf = typeof(MyMath); object[] attributes; attributes = inf.GetCustomAttributes(typeof(BugFixAttribute), false); 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.rument); } } }</source>