原文出处:http://www.codeguru.com/csharp/csharp/cs_syntax/attributes/article.php/c5831/
using attributes in c#
rating: none
sadaf alvi (view profile)
september 24, 2002
environment: c#
introduction
attributes are a new kind of declarative information. we can use attributes to define both design-level information (such as a help file or a url for documentation) and run-time information (such as associating an xml field with a class field). we also can create "self-describing" components using attributes. in this tutorial, we will see how we can create and attach attributes to various program entities, and how we can retrieve attribute information in a run-time environment.
definition
(continued)
as stated in msdn (ms-help://ms.msdnqtr.2002apr.1033/csspec/html/vclrfcsharpspec_17_2.htm):
"an attribute is a piece of additional declarative information that is specified for a declaration."
using pre-defined attributes
there is a small set of pre-defined attributes present in c#. before learning how to create our own custom attributes, we will first look at how to use those in our code.
using system;
public class anyclass
{
[obsolete("don't use old method, use new method", true)]
static void old( )
{
}
static void new( )
{
}
public static void main( )
{
old( );
}
}
take a look at the this example. we use the attribute obsolete, which marks a program entity that should not be used. the first parameter is the string, which explains why the item is obsolete and what to use instead. in fact, you can write any other text here. the second parameter tells the compiler to treat the use of the item as an error. the default value is false, which means the compiler generates a warning for this.
when we try to compile the preceding program, we will get an error:
anyclass.old()' is obsolete: 'don't use old method, use new method'
developing custom attributes
now we will see how we can develop our own attributes. here is a small recipe to create our own attributes.
derive our attribute class from the system.attribute class as stated in the c# language specification (a class that derives from the abstract class system.attribute, whether directly or indirectly, is an attribute class. the declaration of an attribute class defines a new kind of attribute that can be placed on a declaration) and we are done.
using system;
public class helpattribute : attribute
{
}
believe me or not, we have just created a custom attribute. we can decorate our class with it as we did with an obsolete attribute.
[help()] public class anyclass
{
}
note: it is a convention to use the word attribute as a suffix in attribute class names. however, when we attach the attribute to a program entity, we are free not to include the attribute suffix. the compiler first searches the attribute in system.attribute derived classes. if no class is found, the compiler will add the word attribute to the specified attribute name and search for it.
but this attribute does nothing useful so far. to make it a little more useful, let's add something more in it.
using system;
public class helpattribute : attribute
{
public helpattribute(string description_in)
{
this.description = description_in;
}
protected string description; public string description
{
get {
return this.description;
}
}
}
[help("this is a do-nothing class")]
public class anyclass
{
}
in above example, we have added a property to our attribute class. we will query it at runtime in the last section.
defining or controlling the usage of our attribute
attributeusage class is another pre-defined class that will help us control the usage of our custom attributes. that is, we can define attributes of our own attribute class. it describes how a custom attribute class can be used.
attributeusage has three properties that we can set when placing it on our custom attribute. these three properties are discussed in the following sections.
validon
through this property, we can define the program entities on which our custom attribute can be placed. the set of all possible program entities on which an attribute can be placed is listed in the attributetargets enumerator. we can combine several attributetargets values by using a bitwise or operation.
allowmultiple
this property marks whether our custom attribute can be placed more than once on the same program entity.
inherited
we can control the inheritance rules of our attribute by using this property. this property marks whether our attribute will be inherited by the class derived from the class on which we have placed it.
let's do something practical. we will place the attributeusage attribute on our own help attribute and control the usage of our attribute with the help of it.
using system;
[attributeusage(attributetargets.class), allowmultiple = false, inherited = false ]
public class helpattribute : attribute
{
public helpattribute(string description_in)
{
this.description = description_in;
}
protected string description;
public string description
{
get {
return this.description;
}
}
}
first, look at the attributetargets.class. it states that the help attribute can be placed on a class only. this implies that the following code will result in an error:
anyclass.cs: attribute 'help' is not valid on this declaration type. it is valid on 'class' declarations only.
now try to put it in a method:
[help("this is a do-nothing class")]
public class anyclass
{
[help("this is a do-nothing method")] //error
public void anymethod()
{
}
}
we can use attributetargets.all to allow the help attribute to be placed on any program entity (possible values are: assembly, module, class, struct, enum, constructor, method, property, field, event, interface, parameter, delegate, all = assembly | module | class | struct | enum | constructor | method | property | field | event | interface | parameter | delegate, classmembers = class | struct | enum | constructor | method | property | field | event | delegate | interface ).
now consider allowmultiple = false. this states that an attribute cannot be placed multiple times.
[help("this is a do-nothing class")]
[help("it contains a do-nothing method")]
public class anyclass
{
[help("this is a do-nothing method")] //error
public void anymethod()
{
}
}
it generates a compile-time error.
anyclass.cs: duplicate 'help' attribute
okay, now let's discuss the last property. inherited indicates whether the attribute, when placed on a base class, is also inherited by classes that derive from that base class. if inherited for an attribute class is true, that attribute is inherited. however, if inherited for an attribute class is false or it is unspecified, that attribute is not inherited.
let's suppose we have following class relationship.
[help("baseclass")] public class base { } public class derive : base { }
we have four possible combinations:
[attributeusage(attributetargets.class, allowmultiple = false, inherited = false ]
[attributeusage(attributetargets.class, allowmultiple = true, inherited = false ]
[attributeusage(attributetargets.class, allowmultiple = false, inherited = true ]
[attributeusage(attributetargets.class, allowmultiple = true, inherited = true ]
these combinations are discussed in the following sections.
first case
if we query (we will see later how to query the attributes of a class at run-time) the derive class for its help attribute, we will not find it because the inherited attribute is set to false.
second case
the second case is not different; an inherited attribute is set to false in this case, also.
third case
to explain the third and fourth cases, let's add the same attribute to the derive class, also.
[help("baseclass")]
public class base
{
}
[help("deriveclass")]
public class derive : base
{
}
now, if we query about the help attribute, we will get the drive class attribute only because inherited is true, but multiples are not allowed so the base class help is overridden by the derive class help attribute.
fourth case
in the fourth case, we will get both attributes when we query our derive class for the help attribute because both inheritance and multiples are allowed in this case.
note: the attributeusage attribute is only valid on classes derived from system.attribute and both allowmultiple and inherited are false for this attribute.
positional versus named parameters
positional parameters are parameters of the attribute's constructor. they are mandatory and a value must be passed every time the attribute is placed on any program entity. on the other hand, named parameters are actually optional and are not parameters of the attribute's constructor.
to explain it in more detail, let's add another property to our help class.
[attributeusage(attributetargets.class, allowmultiple = false,inherited = false)]
public class helpattribute : attribute
{
public helpattribute(string description_in)
{
this.description = description_in;
this.version = "no version is defined for this class";
}
protected string description;
public string description
{
get {
return this.description;
}
}
protected string version;
public string version
{
get {
return this.version;
}
//if we ever want our attribute user to set this property,
//we must specify set method for it
set {
this.version = value;
}
}
}
[help("this is class1")]
public class class1
{
}
[help("this is class2", version = "1.0")]
public class class2
{
}
[help("this is class3", version = "2.0", description = "this is do-nothing class")]
public class class3
{
}
when we query class1 for the help attribute and its properties, we will get:
help.description : this is class1
help.version :no version is defined for this class
because we didn't define any value for the version property, the value set in the constructor is used. if no value is defined, the default value of the type is used (for example, in case int, the default value is zero).
now, querying class2 will result in the following:
help.description : this is class2
help.version : 1.0
don't use multiple constructors for optional parameters. instead, mark them as named parameters. we called them named because, when we supply their value in the constructor, we have to name them. for example, in second class, we define help.
[help("this is class2", version = "1.0")]
in the attributeusage example, the validon parameter is a positional parameter and inherited and allowmultiple are named parameters.
note: to set the value of named parameter in the constructor of the attribute, we must supply the set method for that property; otherwise, it will generate a compile-time error, such as the following message:
'version' : named attribute argument can't be a read-only property
now what happens when we query class3 for the help attribute and its properties? the result is the same compile-time error.
'description' : named attribute argument can't be a read- only property
now modify the help class and add the set method of description. now the output will be:
help.description : this is do-nothing class help.version : 2.0
what happens behind the scenes is first the constructor is called with positional parameters, and then the set method is called for each named parameter. the value set in the constructor is overriden by the set method.
parameter types
the types of parameters for an attribute class are limited to the following:
bool, byte, char, double, float, int, long, short, string
system. type
object
an enum type, provided that it and any types in which it is nested are publicly accessible
a one-dimensional array involving any of the types listed above
attribute identifiers
let's suppose that we want to place the help attribute on the entire assembly. the first question arises: where should we place that help attribute so that the compiler can determine that it is placed on an entire assembly?? consider another situation: we want to place an attribute on the return type of a method. how would the compiler determine that we are placing it on a method-return-type and not on an entire method??
to resolve such ambiguities, we use an attribute identifier. with the help of attribute identifiers, we can explicitly state the entity on which we are placing the attribute.
for example:
[assembly: help("this a do-nothing assembly")]
the assembly identifier before the help attribute explicitly tells the compiler that this attribute is attached to the entire assembly. the possible identifiers are:
assembly
module
type
method
property
event
field
param
return
querying attributes at run time
we have seen how to create attributes and how to attach them to a program element. now it's time to learn how the user of our class can query this information at run time.
to query a program entity about its attached attributes, we must use reflection. reflection is the ability to discover type information at run time.
we can use the .net framework reflection apis to iterate through the metadata for an entire assembly and produce a list of all classes, types, and methods that have been defined for that assembly.
remember the old help attribute and the anyclass class?
using system;
using system.reflection;
using system.diagnostics;
//attaching help attribute to entire assembly
[assembly : help("this assembly demonstrates custom attributes creation and their run-time query.")]
//our custom attribute class
public class helpattribute : attribute
{
public helpattribute(string description_in)
{
// todo: add constructor logic here
this.description = description_in;
}
protected string description;
public string description
{
get
{
return this.description;
}
}
}
//attaching the help attribute to our anyclass
[helpstring("this is a do-nothing class.")]
public class anyclass
{
//attaching the help attribute to our anymethod
[help("this is a do-nothing method.")]
public void anymethod()
{ }
//attaching help attribute to our anyint field
[help("this is any integer.")]
public int anyint;
}
class queryapp
{
public static void main()
{ }
}
we will add the attribute-query code to our main method in the next two sections.
querying assembly attributes
in the following code, we get the current process name and load the assembly using the loadfrom method of the assembly class. then, we use the getcustomattributes method to get all the custom attributes attached to the current assembly. next, for each statement iterate through all the attributes and try to cast each attribute as a help attribute (casting objects using the as keyword has an advantage that if the cast is invalid, we don't have to worry about an exception being thrown. what will happen instead is that the result will be null). the next line checks whether the cast is valid and not equal to null; then it displays the help property of the attribute.
class queryapp
{
public static void main()
{
helpattribute helpattr;
//querying assembly attributes
string assemblyname; process
p = process.getcurrentprocess();
assemblyname = p.processname + ".exe";
assembly a = assembly.loadfrom(assemblyname);
foreach (attribute attr in a.getcustomattributes(true))
{
helpattr = attr as helpattribute;
if (null != helpattr)
{
console.writeline("description of {0}:/n{1}", assemblyname,helpattr.description);
}
}
}
}
the output of the following program is:
description of queryattribute.exe: this assembly demonstrates custom attributes creation and their run-time query.
press any key to continue.
querying class, method, and field attributes
in the following code, the only unfamiliar item is the first line in the main method.
type type = typeof(anyclass);
it gets the type object associated with our anyclass class using the typeof operator. the rest of the code for querying class attributes is similar to the preceding example and doesn't need any explanation (i think).
for querying a method's and field's attributes, we first get all the methods and fields present in the class; then we query their associated attributes in the same manner as we did class attributes
class queryapp {
public static void main()
{
type type = typeof(anyclass);
helpattribute helpattr;
//querying class attributes
foreach (attribute attr in type.getcustomattributes(true))
{
helpattr = attr as helpattribute;
if (null != helpattr)
{
console.writeline("description of anyclass:/n{0}", helpattr.description);
}
}
//querying class-method attributes
foreach(methodinfo method in type.getmethods())
{
foreach (attribute attr in method.getcustomattributes(true))
{
helpattr = attr as helpattribute;
if (null != helpattr)
{
console.writeline("description of {0}:/n{1}", method.name, helpattr.description);
}
}
}
//querying class-field (only public) attributes
foreach(fieldinfo field in type.getfields())
{
foreach (attribute attr in field.getcustomattributes(true))
{
helpattr= attr as helpattribute;
if (null != helpattr)
{
console.writeline("description of {0}:/n{1}",field.name, helpattr.description);
}
}
}
}
}
the output of the following program is:
description of anyclass: this is a do-nothing class.
description of anymethod: this is a do-nothing method.
description of anyint: this is any integer.
press any key to continue
注册会员,创建你的web开发资料库,