Information Technology Reference
In-Depth Information
class. The .NET class library defines a class called
Type
, which has several methods that you can
use to access this information.
To use these methods, you can start by creating an instance of the class you want to query
and calling the instance's
GetType
method, which returns an object of type
Type
. Every class has
the
GetType
method, because
GetType
is a member of type
object
, which is the base from which
every class is derived.
Using the IsDefined Method
You can use the
IsDefined
method of the
Type
object to determine whether a particular
attribute is applied to a particular class. When this method is called, it returns a
bool
value that
tells whether an attribute is defined on a particular program construct.
For example, the following code declares an attributed class called
MyClass
, and also acts
as its own attribute consumer, by accessing an attribute declared and applied in the program
itself. At the top of the code are declarations of the attribute
MyAttribute
and the class
MyClass
,
to which it is applied. The code does the following:
Firs ,
Main
creates an object of the class. It then retrieves a reference to the
Type
object by
using the
GetType
method, which it inherited from its base class,
object
.
With the reference to the
Type
object, it can call the
IsDefined
method to find out
whether attribute
MyAttribute
is applied to this class.
-
The first parameter takes a
Type
object of the
attribute
you are checking for.
-
The second parameter is of type
bool
and specifies whether to search the inheritance
tree of
MyClass
to find the attribute.
[AttributeUsage(AttributeTargets.Class)]
public sealed class MyAttributeAttribute : System.Attribute
{ ... }
[MyAttribute("Check it out", "2.4")]
class MyClass { }
class Program {
static void Main() {
MyClass mc = new MyClass(); // Create an instance of the class.
Type t = mc.GetType(); // Get the Type object from the instance.
bool ItIsDefined = // Check the Type for the attribute.
t.IsDefined(typeof(MyAttributeAttribute), false);
Console.WriteLine("MyAttribute is applied to type {0}", t.Name);
}
}