forked from dotnet/dotnet-api-docs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdefattr.cs
79 lines (70 loc) · 2.21 KB
/
defattr.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// <Snippet1>
using System;
using System.Reflection;
namespace DefAttrCS
{
// An enumeration of animals. Start at 1 (0 = uninitialized).
public enum Animal
{
// Pets.
Dog = 1,
Cat,
Bird,
}
// A custom attribute to allow a target to have a pet.
public class AnimalTypeAttribute : Attribute
{
// The constructor is called when the attribute is set.
public AnimalTypeAttribute(Animal pet)
{
thePet = pet;
}
// Provide a default constructor and make Dog the default.
public AnimalTypeAttribute()
{
thePet = Animal.Dog;
}
// Keep a variable internally ...
protected Animal thePet;
// .. and show a copy to the outside world.
public Animal Pet
{
get { return thePet; }
set { thePet = Pet; }
}
// Override IsDefaultAttribute to return the correct response.
public override bool IsDefaultAttribute()
{
if (thePet == Animal.Dog)
return true;
return false;
}
}
public class TestClass
{
// Use the default constructor.
[AnimalType]
public void Method1()
{}
}
class DemoClass
{
static void Main(string[] args)
{
// Get the class type to access its metadata.
Type clsType = typeof(TestClass);
// Get type information for the method.
MethodInfo mInfo = clsType.GetMethod("Method1");
// Get the AnimalType attribute for the method.
AnimalTypeAttribute atAttr =
(AnimalTypeAttribute)Attribute.GetCustomAttribute(mInfo,
typeof(AnimalTypeAttribute));
// Check to see if the default attribute is applied.
Console.WriteLine("The attribute {0} for method {1} in class {2}",
atAttr.Pet, mInfo.Name, clsType.Name);
Console.WriteLine("{0} the default for the AnimalType attribute.",
atAttr.IsDefaultAttribute() ? "is" : "is not");
}
}
}
// </Snippet1>