|
|||||
|
Attributes are a powerful method of associating declarative information with C# code (types, methods, properties, etc.). Once associated with a program entity, the attribute can be queried at run time and used in many ways. C# attributes are not to be confused with HTML attributes or object-oriented member variables which too are often called attributes. An attribute is a tag of meta-data that can be applied to a particular construct. For example you can apply an attribute to a class, a method, or a property. At first, we must understand, that attributes are "just" classes that derives from System.Attribute. For defining a new attribute, we must write a class. Let's look an example - Color attribute for figures public class ColorAttribute : Attribute
{
public string whichColor;
public ColorAttribute(string color)
{
this.whichColor = color;
}
}
Le's see how we use it : [Color("No color")] // figures have no color by default
public class Figure
{
}
[Color("Red")]// All rectangles are to be colored red
public class Rectangle : Figure
{
}
[Color("Blue")]// Circles are to be colored blue
public class Circle : Figure
{
}
Attributes can be queried during run-time: public string WhichColorIsTheFigure(Figure fig)
{
Type type=fig.GetType();// Get object type
object obj=type.GetCustomAttributes()[0];// Get first attribute
if(obj is ColorAttribute)
return ((ColorAttribute)obj).whichColor;
}
|