Export (0) Print
Expand All
4 out of 9 rated this helpful - Rate this topic

Attribute Class

Base class for custom attributes.

For a list of all members of this type, see Attribute Members.

System.Object
   System.Attribute
      Derived classes

[Visual Basic]
<AttributeUsage(AttributeTargets.All)>
<Serializable>
MustInherit Public Class Attribute
[C#]
[AttributeUsage(AttributeTargets.All)]
[Serializable]
public abstract class Attribute
[C++]
[AttributeUsage(AttributeTargets::All)]
[Serializable]
public __gc __abstract class Attribute
[JScript]
public
   AttributeUsage(AttributeTargets.All)
 Serializable
abstract class Attribute

Thread Safety

This type is safe for multithreaded operations.

Remarks

The Attribute class contains convenience methods to access and test custom attributes. While any user-defined type can be used as an attribute, it is expected that most attributes will be instances of types derived from Attribute.

All attributes derive directly or indirectly from Attribute. Attributes can be applied to any target element (see AttributeTargets); multiple instances of an attribute can be applied to the same target element; and attributes can be inherited by an element derived from a target element. Compilers and other development tools use this information to identify which attributes are custom attributes.

Custom attributes can be stored with any element of the metadata. This mechanism can be used to store application-specific information at compile time and access it either at runtime or when another tool reads the metadata.

.NET Framework predefines some attribute types and uses them to control runtime behavior. Some languages predefine attribute types to represent language features not directly represented in the .NET Framework common type system. Users or other tools are welcome to define and use additional attribute types.

For more information about using attributes, see Extending Metadata Using Attributes.

Example

The following code example demonstrates the usage of Attribute:

[Visual Basic] 
Imports System
Imports System.Reflection

Public Module CustomAttrVB

    ' An enumeration of animals. Start at 1 (0 = uninitialized).
    Public Enum Animal
        ' Pets
        Dog = 1
        Cat
        Bird
    End Enum

    ' Visual Basic requires the AttributeUsage be specified.
    ' A custom attribute to allow a target to have a pet.
    <AttributeUsage(AttributeTargets.Method)> _
    Public Class AnimalTypeAttribute
        Inherits Attribute

        ' The constructor is called when the attribute is set.
        Public Sub New(ByVal animal As Animal)
            Me.thePet = animal
        End Sub

        ' Keep a variable internally ...
        Protected thePet As Animal

        ' .. and show a copy to the outside world.
        Public Property Pet() As Animal
            Get
                Return thePet
            End Get
            Set(ByVal Value As Animal)
                thePet = Value
            End Set
        End Property

    End Class

    ' A test class where each method has its own pet.
    Class AnimalTypeTestClass

        <AnimalType(Animal.Dog)> _
        Public Sub DogMethod()
        End Sub

        <AnimalType(Animal.Cat)> _
        Public Sub CatMethod()
        End Sub

        <AnimalType(Animal.Bird)> _
        Public Sub BirdMethod()
        End Sub
    End Class

    ' The runtime test.
    Sub Main()
        Dim testClass As New AnimalTypeTestClass()
        Dim tcType As Type = testClass.GetType()
        Dim mInfo As MethodInfo
        ' Iterate through all the methods of the class.
        For Each mInfo In tcType.GetMethods()
            Dim attr As Attribute
            ' Iterate through all the attributes of the method.
            For Each attr In Attribute.GetCustomAttributes(mInfo)
                If TypeOf attr Is AnimalTypeAttribute Then
                    Dim attrCustom As AnimalTypeAttribute = _
                        CType(attr, AnimalTypeAttribute)
                    Console.WriteLine("Method {0} has a pet {1} attribute.", _
                         mInfo.Name(), attrCustom.Pet.ToString())
                End If
            Next
        Next
    End Sub
End Module

' Output:
' Method DogMethod has a pet Dog attribute.
' Method CatMethod has a pet Cat attribute.
' Method BirdMethod has a pet Bird attribute.

[C#] 
using System;
using System.Reflection;

namespace CustomAttrCS {
    // 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;
        }

        // Keep a variable internally ...
        protected Animal thePet;

        // .. and show a copy to the outside world.
        public Animal Pet {
            get { return thePet; }
            set { thePet = Pet; }
        }
    }

    // A test class where each method has its own pet.
    class AnimalTypeTestClass {
        [AnimalType(Animal.Dog)]
        public void DogMethod() {}

        [AnimalType(Animal.Cat)]
        public void CatMethod() {}

        [AnimalType(Animal.Bird)]
        public void BirdMethod() {}
    }

    class DemoClass {
        static void Main(string[] args) {
            AnimalTypeTestClass testClass = new AnimalTypeTestClass();
            Type type = testClass.GetType();
            // Iterate through all the methods of the class.
            foreach(MethodInfo mInfo in type.GetMethods()) {
                // Iterate through all the Attributes for each method.
                foreach (Attribute attr in 
                    Attribute.GetCustomAttributes(mInfo)) {
                    // Check for the AnimalType attribute.
                    if (attr.GetType() == typeof(AnimalTypeAttribute))
                        Console.WriteLine(
                            "Method {0} has a pet {1} attribute.", 
                            mInfo.Name, ((AnimalTypeAttribute)attr).Pet);
                }

            }
        }
    }
}

/*
 * Output:
 * Method DogMethod has a pet Dog attribute.
 * Method CatMethod has a pet Cat attribute.
 * Method BirdMethod has a pet Bird attribute.
 */

[C++] 
#using <mscorlib.dll>
using namespace System;
using namespace System::Reflection;

// An enumeration of animals. Start at 1 (0 = uninitialized).
public __value enum Animal {
   // Pets.
   Dog = 1,
   Cat,
   Bird,
};

// A custom attribute to allow a target to have a pet.
public __gc class AnimalTypeAttribute : public Attribute {
   // The constructor is called when the attribute is set.
public:
   AnimalTypeAttribute(Animal pet) {
      thePet = pet;
   }

   // Keep a variable internally ...
protected:
   Animal thePet;

   // .. and show a copy to the outside world.
public:
   __property Animal get_Pet() { return thePet; }
   __property void set_Pet( Animal value ) { thePet = value; }

};

// A test class where each method has its own pet.
__gc class AnimalTypeTestClass {
public:
   [AnimalType(Animal::Dog)]
   void DogMethod() {}

   [AnimalType(Animal::Cat)]
   void CatMethod() {}

   [AnimalType(Animal::Bird)]
   void BirdMethod() {}
};

int main() {
   AnimalTypeTestClass* testClass = new AnimalTypeTestClass();
   Type* type = testClass->GetType();
   // Iterate through all the methods of the class.
   System::Collections::IEnumerator* myEnum = type->GetMethods()->GetEnumerator();
   while (myEnum->MoveNext())
   {
      MethodInfo* mInfo = __try_cast<MethodInfo*>(myEnum->Current);
      // Iterate through all the Attributes for each method.
      System::Collections::IEnumerator* myEnum1 = Attribute::GetCustomAttributes(mInfo)->GetEnumerator();
      while (myEnum1->MoveNext())
      {
         Attribute* attr = __try_cast<Attribute*>(myEnum1->Current);
         // Check for the AnimalType attribute.
         if (attr->GetType() == __typeof(AnimalTypeAttribute))
            Console::WriteLine(
            S"Method {0} has a pet {1} attribute.", 
            mInfo->Name, __box((dynamic_cast<AnimalTypeAttribute*>(attr))->Pet));
      }

   }
}

/*
 * Output:
 * Method DogMethod has a pet Dog attribute.
 * Method CatMethod has a pet Cat attribute.
 * Method BirdMethod has a pet Bird attribute.
 */

[JScript] 
import System;
import System.Reflection;
import CustomAttrJS;

package CustomAttrJS {
    // 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 AttributeUsage(AttributeTargets.Method) class AnimalTypeAttribute extends Attribute {
        // The constructor is called when the attribute is set.
        public function AnimalTypeAttribute(pet : Animal) {
            thePet = pet;
        }

        // Keep a variable internally ...
        protected var thePet : Animal;

        // .. and show a copy to the outside world.
        public function get Pet() : Animal {
                    return thePet; 
                }
        
                public function set Pet(pet : Animal) {
                    thePet = pet; 
                }
    }

    // A test class where each method has its own pet.
    class AnimalTypeTestClass {
        public AnimalTypeAttribute(Animal.Dog) 
                function DogMethod() {}

        public AnimalTypeAttribute(Animal.Cat)
        function CatMethod() {}

        public AnimalTypeAttribute(Animal.Bird)
        function BirdMethod() {}
    }
}



var testClass : AnimalTypeTestClass = new AnimalTypeTestClass();
var type : Type = testClass.GetType();
// Iterate through all the methods of the class.
            var mInfo : MethodInfo[] = type.GetMethods();
for (var i : int = 0; i < mInfo.length; i++) {
    // Iterate through all the Attributes for each method.
                    var attr : Attribute[] = Attribute.GetCustomAttributes(mInfo[i]);
    for (var j : int = 0; j < attr.length; j++) 
    {
        // Check for the AnimalType attribute.
        if (attr[j].GetType() == AnimalTypeAttribute)
            Console.WriteLine(
                "Method {0} has a pet {1} attribute.", 
                mInfo[i].Name, AnimalTypeAttribute(attr[j]).Pet);
    }

}


/*
 * Output:
 * Method BirdMethod has a pet Bird attribute.
 * Method CatMethod has a pet Cat attribute.
 * Method DogMethod has a pet Dog attribute.
 *
 */

Requirements

Namespace: System

Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family, .NET Compact Framework

Assembly: Mscorlib (in Mscorlib.dll)

See Also

Attribute Members | System Namespace

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.