Export (0) Print
Expand All
3 out of 6 rated this helpful - Rate this topic

Attribute Class

Represents the base class for custom attributes.

Namespace: System
Assembly: mscorlib (in mscorlib.dll)

[SerializableAttribute] 
[ComVisibleAttribute(true)] 
[AttributeUsageAttribute(AttributeTargets.All, Inherited=true, AllowMultiple=false)] 
[ClassInterfaceAttribute(ClassInterfaceType.None)] 
public abstract class Attribute : _Attribute
/** @attribute SerializableAttribute() */ 
/** @attribute ComVisibleAttribute(true) */ 
/** @attribute AttributeUsageAttribute(AttributeTargets.All, Inherited=true, AllowMultiple=false) */ 
/** @attribute ClassInterfaceAttribute(ClassInterfaceType.None) */ 
public abstract class Attribute implements _Attribute
SerializableAttribute 
ComVisibleAttribute(true) 
AttributeUsageAttribute(AttributeTargets.All, Inherited=true, AllowMultiple=false) 
ClassInterfaceAttribute(ClassInterfaceType.None) 
public abstract class Attribute implements _Attribute
Not applicable.

The Attribute class associates predefined system information or user-defined custom information with a target element. A target element can be an assembly, class, constructor, delegate, enum, event, field, interface, method, portable executable file module, parameter, property, return value, struct, or another attribute.

Information provided by an attribute is also known as metadata. Metadata can be examined at run time by your application to control how your program processes data, or before run time by external tools to control how your application itself is processed or maintained. For example, the .NET Framework predefines and uses attribute types to control run-time behavior, and some programming languages use attribute types to represent language features not directly supported by the .NET Framework common type system.

All attribute types derive directly or indirectly from the Attribute class. Attributes can be applied to any target element; multiple attributes can be applied to the same target element; and attributes can be inherited by an element derived from a target element. Use the AttributeTargets class to specify the target element to which the attribute is applied.

The Attribute class provides convenient methods to retrieve and test custom attributes. For more information about using attributes, see Applying Attributes and Extending Metadata Using Attributes.

The following code example demonstrates the usage of Attribute.

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.
 */


package CustomAttrJSL; 

import System.*;
import System.Reflection.*;
  
public class Animal
{
    protected int pet;
    public static final int dog = 1;
    public static final int cat = 2;
    public static final int bird = 3;

    public Animal()
    {
        pet = 0;
    } //Animal
    public Animal(int p)
    {
        pet = p;
    } //Animal
    public String getPet()
    {
        switch (pet) {
            case 1 :
                return "Dog";
            case 2 :
                return "Cat";
            case 3 :
                return "Bird";
            default :
                return null;
        }
    } //getPet
} //Animal
      
// A custom attribute to allow a target to have a pet.
/** @attribute System.AttributeUsageAttribute(AttributeTargets.Method)
 */
public class AnimalTypeAttribute extends Attribute
{
    public AnimalTypeAttribute() { }
    // The constructor is called when the attribute is set.
    public AnimalTypeAttribute(int pet)
    {
        thePet = new Animal(pet);
    } //AnimalTypeAttribute

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

    //.. and show a copy to the outside world.
    /** @property 
     */
    public Animal get_Pet()
    {
        return thePet;
    } //get_Pet

    /** @property 
     */
    public void set_Pet(Animal value)
    {
        thePet = value;
    } //set_Pet
} //AnimalTypeAttribute
      
 // A test class where each method has its own pet.
class AnimalTypeTestClass
{
    /** @attribute AnimalType(Animal.dog)
     */
    public void DogMethod()
    {
    } //DogMethod

    /** @attribute AnimalType(Animal.cat)
     */
    public void CatMethod()
    {
    } //CatMethod

    /** @attribute AnimalType(Animal.bird)
     */
    public void BirdMethod()
    {
    } //BirdMethod
} //AnimalTypeTestClass
   
class DemoClass
{
    public static void main(String[] args)
    {
        AnimalTypeTestClass testClass = new AnimalTypeTestClass();
        Type type = testClass.GetType();
        // Iterate through all the methods of the class.
        for (int iCtr1 = 0; iCtr1 < type.GetMethods().length; iCtr1++) {
            MethodInfo mInfo = type.GetMethods()[iCtr1];
            // Iterate through all the Attributes for each method.
            for (int iCtr2 = 0; 
                iCtr2 < Attribute.GetCustomAttributes(mInfo).length; 
                iCtr2++) {
               
                Attribute attr = Attribute.GetCustomAttributes(mInfo)[iCtr2];
                // Check for the AnimalType attribute.
                if (attr.GetType().
                    Equals(AnimalTypeAttribute.class.ToType())) {                
                    Console.WriteLine("Method {0} has a pet {1} attribute.", 
                        mInfo.get_Name(), 
                        ((AnimalTypeAttribute)attr).get_Pet().getPet());
                }
            }
        }
    } //main
} //DemoClass 

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

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.
 *
 */

This type is thread safe.

Windows 98, Windows Server 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The Microsoft .NET Framework 3.0 is supported on Windows Vista, Microsoft Windows XP SP2, and Windows Server 2003 SP1.

.NET Framework

Supported in: 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 2.0, 1.0

XNA Framework

Supported in: 1.0
Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

ADD
Show:
© 2014 Microsoft. All rights reserved.