Csharp/C Sharp by API/System/AttributeTargets
AttributeTargets.All
using System;
using System.Reflection;
[AttributeUsage(AttributeTargets.All)]
class RemarkAttribute : Attribute {
string remarkValue;
public RemarkAttribute(string comment) {
remarkValue = comment;
}
public string remark {
get {
return remarkValue;
}
}
}
[RemarkAttribute("This class uses an attribute.")]
class UseAttrib {
// ...
}
public class AttribDemo {
public static void Main() {
Type t = typeof(UseAttrib);
Console.Write("Attributes in " + t.Name + ": ");
object[] attribs = t.GetCustomAttributes(false);
foreach(object o in attribs) {
Console.WriteLine(o);
}
Console.Write("Remark: ");
// Retrieve the RemarkAttribute.
Type tRemAtt = typeof(RemarkAttribute);
RemarkAttribute ra = (RemarkAttribute)
Attribute.GetCustomAttribute(t, tRemAtt);
Console.WriteLine(ra.remark);
}
}
AttributeTargets.Class
using System;
using System.Reflection;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
public class Creator : System.Attribute {
public Creator(string name, string date) {
this.name = name;
this.date = date;
version = 0.1;
}
string date;
string name;
public double version;
}
[Creator("T", "05/01/2001", version = 1.1)]
class MainClass {
static public void Main(String[] args) {
for (int i = 0; i < args.Length; ++i)
System.Console.WriteLine("Args[{0}] = {1}", i, args[i]);
}
}
AttributeTargets.Struct
using System;
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct,Inherited = false)]
public class ClassVersionAttribute : System.Attribute {
public ClassVersionAttribute(string target) : this(target, target) {
}
public ClassVersionAttribute(string target,string current) {
m_TargetVersion = target;
m_CurrentVersion = current;
}
private bool m_UseCurrentVersion = false;
public bool UseCurrentVersion {
set {
if (m_TargetVersion != m_CurrentVersion) {
m_UseCurrentVersion = value;
}
}
get {
return m_UseCurrentVersion;
}
}
private string m_CurrentName;
public string CurrentName {
set {
m_CurrentName = value;
}
get {
return m_CurrentName;
}
}
private string m_TargetVersion;
public string TargetVersion {
get {
return m_TargetVersion;
}
}
private string m_CurrentVersion;
public string CurrentVersion {
get {
return m_CurrentVersion;
}
}
}