Imagine you associate information with some class you wrote... How you do it?
You can write some doc for you classes, or in COM - IDL file, or other.. .NET framework, and than C# gives new,flexible soulition named attributes. For example:
Serializable
class x
{
public int x,y;
}
says, that class "x" may be serialized in some point of time. Such additional information about our class may help us remember, what is class about. But, .NET says more: attributes can be queried at runtime! Says, I can "define" my private custom attribute, that will mean exactly what I want and know about any class at runtime, which it has such attribute.
How does .NET do it?
At first, we must understand, that attributes are "just" classes that derives from System.Attribute.
So, for defining new attribute we must wrote class. Let's look an example - Meou attribute for cat
classes describes why some kind of cats says "Meou".
public class MeouAttribute? : Attribute
{
public string Why;
public MeouAttribute(string Why)
{
this.Why=Why;
}
}
So, by wroting those lines we have defined custom attribute! Let's use it:
Meou("No reason") // normal cats say meou without reason
public class Cat
{
}
Meou("I'm hungry")// hungry cats meou, becouse they want eat
public class HungryCat? : Cat
{
}
Meou("Pussy..")// pussy cats - no comments
public class PussyCat? : Cat
{
}
Okay,- say you,- nice. But what we can do with this attributes? Here .NET gives our new point of the view: runtime attributes querying. How? Let's write little function receives can and determines, why him sayd "Meou".
public string WhyISaidMeou(Cat cat)
{
Type type=cat.GetType();// Get object type
object obj=type.GetCustomAttributes()0;// Get first attribute
if(obj is MeouAttribute)// If it's Meou
return ((MeouAttribute)obj).Why;
else// other attribute
return "First attribute is not Meou!";
}
Simple? Yes! Now use it:
Cat cat1=new Cat();
Cat cat2=new HungryCat();
Cat cat3=new PussyCat();
string why1,why2,why3;
why1=WhyISaidMeou(cat1);// receives "No reason"
why2=WhyISaidMeou(cat2);// "hungry"
why3=WhyISaidMeou(cat3);// "pussy"
Application.Exit();
That's all about custom attributes.
0 comments:
Post a Comment