Module 14: Attributes 1
Overview
Overview of Attributes
Defining Custom Attributes
Retrieving Attribute Values
*****************************
ILLEGAL FOR NON-TRAINER USE******************************
Attributes are a simple technique for adding metadata to classes. They can be
useful when you need to build components.
In this module, you will learn the purpose of attributes and the function that
they perform in C# applications. You will learn about attribute syntax and how
to use some of the predefined attributes in the Microsoft
® .NET Framework
environment. You will also learn to create custom user-defined attributes.
Finally, you will learn how classes and other object types can implement and
use these custom attributes to query attribute information at run time.
After completing this module, you will be able to:
Use common predefined attributes.
Create simple custom attributes.
Query attribute information at run time.
Topic Objective
To provide an overview of
the module topics and
objectives.
Lead-in
In this module, you will learn
about using attributes in C#.
Delivery Tip
Teach this module if time
permits. This is a stand-
alone module that does not
have anything else
dependent upon it.
2 Module 14: Attributes
Overview of Attributes
Introduction to Attributes
Applying Attributes
Common Predefined Attributes
Using the Conditional Attribute
Using the DllImport Attribute
Using the Transaction Attribute
*****************************
ILLEGAL FOR NON-TRAINER USE******************************
With the introduction of attributes, the C# language provides a convenient
technique that will help handle tasks such as changing the behavior of the
runtime, obtaining transaction information about an object, conveying
organizational information to a designer, and handling unmanaged code.
After completing this lesson, you will be able to:
Identify which tasks you can perform with attributes.
Use the syntax for using attributes in your code.
Identify some of the predefined attributes that are available in the .NET
Framework.
Topic Objective
To introduce the topics
covered in this section.
Lead-in
In this section, you will learn
what attributes are and how
they are used.
Module 14: Attributes 3
Introduction to Attributes
Attributes are:
Declarative tags that convey information to the runtime
Stored with the metadata of the element
.NET Framework provides predefined attributes
The runtime contains code to examine values of
attributes and act on them
*****************************
ILLEGAL FOR NON-TRAINER USE******************************
The .NET Framework provides attributes so that you can extend the capabilities
of the C# language. An attribute is a declarative tag that you use to convey
information to the runtime about the behavior of programmatic elements such
as classes, enumerators, and assemblies.
You can think of attributes as annotations that your programs can store and use.
In most cases, you write the code that retrieves the values of an attribute in
addition to the code that performs a change in behavior at run time. In its
simplest form, an attribute is an extended way to document your code.
You can apply attributes to many elements of the source code. Information
about the attributes is stored with the metadata of the elements they are
associated with.
The .NET Framework is equipped with a number of predefined attributes. The
code to examine them and act upon the values they contain is also incorporated
as a part of the runtime and .NET Framework SDK.
Topic Objective
To define attributes.
Lead-in
The concept of an attribute
is simple.
Delivery Tip
Stress that attributes are
fundamentally a very simple
idea—they are simply
annotations for your code
that are intended to convey
useful declarative
information.
4 Module 14: Attributes
Applying Attributes
Syntax: Use square brackets to specify an attribute
To apply multiple attributes to an element, you can:
Specify multiple attributes in separate square brackets
Use a single square bracket and separate attributes with
commas
For some elements such as assemblies, specify the
element name associated with the attribute explicitly
[attribute(positional_parameters,named_parameter=value, )]
element
[attribute(positional_parameters,named_parameter=value, )]
element
*****************************
ILLEGAL FOR NON-TRAINER USE******************************
You can apply attributes to different kinds of programming elements. These
elements include assemblies, modules, classes, structs, enums, constructors,
methods, properties, fields, events, interfaces, parameters, return values, and
delegates.
Attribute Syntax
To specify an attribute and associate it with a programming element, use the
following general syntax:
[attribute(positional_parameters,name_parameter=value, )]
element
You specify an attribute name and its values within square brackets ([ and ])
before the programmatic element to which you want to apply the attribute. Most
attributes take one or more parameters, which can be either positional or
named.
You specify a positional parameter in a defined position in the parameter list, as
you would specify parameters for methods. Any named parameter values
follow the positional parameters. Positional parameters are used to specify
essential information, whereas named parameters are used to convey optional
information in an attribute.
Before using an unfamiliar attribute, it is a good practice to check the
documentation for the attribute to find out which parameters are available and
whether they should be positional or named.
Topic Objective
To explain the syntax for
using attributes.
Lead-in
Attributes can be applied to
several different types of
programming elements.
Tip
Module 14: Attributes 5
Example
As an example of using attributes, consider the following code, in which the
DefaultEvent attribute is applied on a class by using a positional string
parameter, ShowResult:
using System.ComponentModel;
[DefaultEvent("ShowResult")]
public class Calculator: System.Windows.Forms.UserControl
{
}
Applying Multiple Attributes
You can apply more than one attribute to an element. You can enclose each
attribute in its own set of square brackets, although you can also enclose
multiple attributes, separated with commas, in the same set of square brackets.
In some circumstances, you must specify exactly which element an attribute is
associated with. For example, in the case of assembly attributes, place them
after any using clauses but before any code, and explicitly specify them as
attributes of the assembly.
The following example shows how to use the CLSCompliant assembly
attribute. This attribute indicates whether or not an assembly strictly conforms
to the Common Language Specification.
using System;
[assembly:CLSCompliant(true)]
class MyClass
{
}
6 Module 14: Attributes
Common Predefined Attributes
.NET provides many predefined attributes
General attributes
COM interoperability attributes
Transaction handling attributes
Visual designer component building attributes
*****************************
ILLEGAL FOR NON-TRAINER USE******************************
The capabilities of predefined attributes in the .NET Framework encompass a
wide range of areas, from interoperability with COM to compatibility with
visual design tools.
This topic describes some of the common predefined attributes that are
provided by the .NET Framework. However, it is not intended to be
comprehensive. For more information about predefined attributes, refer to the
Microsoft Visual Studio
® .NET Help documents.
General Attributes
The following list summarizes some of the general attributes that are provided
by the .NET Framework.
Attribute Applicable to Description
Conditional Method Tests to see whether a named symbol is
defined. If it is defined, any calls to the
method are executed normally. If the symbol
is not defined, the call is not generated.
DllImport Method Indicates that the method is implemented in
unmanaged code, in the specified DLL. It
causes the DLL to be loaded at run time and
the named method to execute.
Topic Objective
To list some common
predefined attributes.
Lead-in
The .NET Framework
provides a large number of
predefined attributes.
Module 14: Attributes 7
COM Interoperability Attributes
When using the attributes to provide interoperability with COM, the goal is to
ensure that using COM components from the managed .NET Framework
environment is as seamless as possible. The .NET Framework has many
attributes relating to COM interoperability. Some of these are listed in the
following table.
Attribute Applicable to Description
ComImport Class/Interface Indicates that a class or interface
definition was imported from a COM
type library.
ComRegisterFunction Method Specifies the method to be called when a
.NET Framework assembly is registered
for use from COM.
ComUnregisterFunction Method Specifies the method to be called when a
.NET assembly is unregistered for use
from COM.
DispId Method, field,
property
Indicates which dispatch ID is to be used
for the method, field or property.
In parameter Indicates that the data should be
marshaled from the caller to the callee.
MarshalAs Field,
parameter,
return values
Specifies how data should be marshaled
between COM and the managed
environment.
ProgId Class Specifies which prog ID is to be used for
the class.
Out parameter Indicates that data should be marshaled
from the callee back to caller.
InterfaceType Interface Specifies whether a managed interface is
IDispatch, IUnknown, or dual when it
is exposed to COM.
For more information about COM interoperability, search for “Microsoft
ComServices” in the .NET Framework SDK Help documents.
Transaction Handling Attributes
Components running in a COM+ environment use transaction management.
The attribute you use for this purpose is shown in the following table.
Attribute Applicable to Description
Transaction Class Specify the type of transaction that should be
available to this object.
Delivery Tip
Avoid getting into long
conversations about COM,
transactions, and
interoperability because this
is beyond the scope of this
course. This information is
presented to show that the
.NET Framework is
compatible with COM.
8 Module 14: Attributes
Visual Designer Component-Building Attributes
Developers who build components for a visual designer use the attributes listed
in the following table.
Attribute Applicable to Description
Bindable Property Specifies whether a property is typically used
for binding.
DefaultProperty Class Specifies the default property for the
component.
DefaultValue Property Indicates that the property is the default value
for the component.
Localizable Property When code is generated for a component,
members that are marked with
Localizable(true) have their property values
saved in resource files. You can localize these
resource files without modifying the code.
DefaultEvent Class Specifies the default event for the component.
Category Property,
event
Specifies the category into which the visual
designer should place this property or event in
the property window.
Description Property,
event
Defines a brief piece of text to be displayed at
the bottom of the property window in the visual
designer when this property or event is selected.
Module 14: Attributes 9
Using the Conditional Attribute
Serves as a debugging tool
Causes conditional compilation of method calls, depending on the
value of a programmer-defined symbol
Does not cause conditional compilation of the method itself
Restrictions on methods
Must have return type of void
Must not be declared as override
Must not be from an inherited interface
using System.Diagnostics;
class MyClass
{
[Conditional ("DEBUGGING")]
public static void MyMethod( )
{
}
}
using System.Diagnostics;
class MyClass
{
[Conditional ("DEBUGGING")]
public static void MyMethod( )
{
}
}
*****************************
ILLEGAL FOR NON-TRAINER USE******************************
You can use the Conditional attribute as a debugging aid in your C# code. This
attribute causes conditional compilation of method calls, depending on the
value of a symbol that you define. It lets you invoke methods that, for example,
display the values of variables, while you test and debug code. After you have
debugged your program, you can “undefine” the symbol and recompile your
code without changing anything else. (Or you can simply remove the symbol
from the command line, and not change anything.)
Example
The following example shows how to use the Conditional attribute. In this
example, the MyMethod method in MyClass is tagged with the Conditional
attribute by the symbol DEBUGGING:
using System.Diagnostics;
class MyClass
{
[Conditional ("DEBUGGING")]
public static void MyMethod( )
{
}
}
Topic Objective
To show how to use the
Conditional attribute.
Lead-in
The Conditional attribute is
frequently used for
debugging classes.
Delivery Tip
The Conditional attribute is
common and is used in the
labs. Make sure students
understand how to use it.
10 Module 14: Attributes
The symbol DEBUGGING is defined as follows:
#define DEBUGGING
class AnotherClass
{
public static void Test( )
{
MyClass.MyMethod( );
}
}
As long as the symbol DEBUGGING remains defined when the method call is
compiled, the method call will operate normally. When DEBUGGING is
undefined, the compiler will omit calls to the method. Therefore, when you run
the program, it will be treated as though that line of code does not exist.
You can define the symbol in one of two ways. You can either add a #define
directive to the code as shown in the preceding example, or define the symbol
from the command line when you compile your program.
Restrictions on Methods
The methods to which you can apply a Conditional attribute are subject to a
number of restrictions. In particular, they must have a return type of void, they
must not be marked as override, and they must not be the implementation of a
method from an inherited interface.
The Conditional attribute does not cause conditional compilation of the
method itself. The attribute only determines the action that will occur when the
method is called. If you require conditional compilation of a method, then you
must use the #if and #endif directives in your code.
Note
Không có nhận xét nào:
Đăng nhận xét