, . . public. System. Attribute.
AttributeUsageAttribute, . , , , . AttributeUsageAttribute
[AttributeUsage(AttributeTargets.All, Inherited = false,
AllowMultiple = true)]
System. AttributeUsageAttribute , . : AttributeTargets, Inherited AllowMultiple.
AttributeTargets
AttributeTargets.All. , . , AttributeTargets.Class, , , AttributeTargets.Method . .
AttributeTargets. , :
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
Inherited , , , . : true false. Inherited = true.
AllowMultiple
, . false, .
.
using System;
namespace test
{ //
[AttributeUsage(AttributeTargets.All, Inherited = false,
AllowMultiple = true)]
public class TestAttribute: System.Attribute
{ //
private string name;
private int kod;
// Name
public virtual string Name
{ get
{ return name;
}
}
// Kod
public int Kod
{ get { return kod; }
set {kod = value; } //
//
}
//
public TestAttribute(string name)
{ this.name = name;
this.kod = 12345;
}
}
//
, TestAttribute System. Attribute. TestAttribute ,
[AttributeUsage(AttributeTargets.All, Inherited = false,
AllowMultiple = true)]
|
|
name string kod int.
Name Kod . , .
name string. name.
, . , Name Kod, . , .
Test. TestAttribute Test.
[TestAttribute("Hallow Word")]
[TestAttribute("Hallow Word"), Kod=123]
.
//
[TestAttribute("Hallow Word", Kod=123)] //
class Test
{ static void Main()
{ //
GetAttribute(typeof(Test));
}
public static void GetAttribute(Type t)
{ // TestAttribute Test
TestAttribute att=
(TestAttribute) Attribute.GetCustomAttribute(t,
typeof(TestAttribute));
// TestAttribute
Console.WriteLine("{0}", att.Name);
}
}
}
Test GetAttribute Name . GetCustomAttribute Attribute. Test, , TestAttribute. , Name.
GetAttribute Main.
"Hallow Word".