Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 40 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
40
Dung lượng
847,73 KB
Nội dung
Contents
Overview 1
Overview of Attributes 2
Defining Custom Attributes 13
Retrieving Attribute Values 22
Lab 14.1: Defining and Using Attributes 26
Review 34
Course Evaluation 36
Module 14:Attributes
Information in this document, including URL and other Internet Web site references, is subject to
change without notice. Unless otherwise noted, the example companies, organizations, products,
domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious,
and no association with any real company, organization, product, domain name, e-mail address,
logo, person, places or events is intended or should be inferred. Complying with all applicable
copyright laws is the responsibility of the user. Without limiting the rights under copyright, no
part of this document may be reproduced, stored in or introduced into a retrieval system, or
transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or
otherwise), or for any purpose, without the express written permission of Microsoft Corporation.
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.
2001−2002 Microsoft Corporation. All rights reserved.
Microsoft, MS-DOS, Windows, Windows NT, ActiveX, BizTalk, IntelliSense, JScript, MSDN,
PowerPoint, SQL Server, Visual Basic, Visual C++, Visual C#, Visual J#, Visual Studio, and
Win32 are either registered trademarks or trademarks of Microsoft Corporation in the U.S.A.
and/or other countries.
The names of actual companies and products mentioned herein may be the trademarks of their
respective owners.
Module14:Attributes iii
Instructor Notes
Teach this module if time permits. Module 14 is a stand-alone module that does
not have anything else dependent upon it.
This module provides students with the details about how to use attributes in
code. It describes the predefined attributes that are provided by the Microsoft
®
.NET Framework and provides some simple examples of how to use some
common attributes. The concept of custom attributes is introduced. This
introduction is followed by a detailed explanation of how to define and use
custom attributes. The process used to compile code that has custom attributes
is also explained. Finally, the module describes how to retrieve attribute values
during run time by using reflection. The procedure that is used to retrieve
attribute information into an array and query the array to obtain the required
values is explained.
After completing this module, students will be able to:
Use common predefined attributes.
Create simple custom attributes.
Query attribute information at run time.
Materials and Preparation
This section provides the materials and preparation tasks that you need to teach
this module.
Required Materials
To teach this module, you need the following materials:
Microsoft PowerPoint® file 2124C_14.ppt
Module 14, “Attributes”
Lab 14, Defining and Using Attributes
Preparation Tasks
To prepare for this module, you should:
Read all of the materials for this module.
Complete the lab.
Read the instructor notes and margin notes for the module.
Practice using Intermediate Language Disassembler (ILDASM) to examine
the metadata of an assembly.
Presentation:
60 Minutes
Lab:
45 Minutes
iv Module14:Attributes
Module Strategy
Use the following strategy to present this module:
Overview of Attributes
Begin by explaining that attributes are only annotations to classes and
perform no function themselves. Before attributes can cause an action,
certain code must be implemented. This code is in the runtime for the
predefined attributes and is written by the developer for custom attributes.
Explain the syntax used to apply an attribute, and, after covering the lists of
predefined attributes briefly, discuss the three attributes—Conditional,
DllImport, and Transaction—using examples.
Defining Custom Attributes
Introduce the need for creating custom attributes, and explain the procedures
involved in defining a custom attribute. Explain the use of AttributeUsage
and how to create an attribute class. Then explain the details of the
procedure used to compile code that uses custom attributes. Finish the
section by explaining how to use multiple attributes in code.
Retrieving Attribute Values
In this section, introduce the concept of retrieving attribute values at run
time by using reflection. Explain how to use the MemberInfo class and the
typeof operator to obtain attribute values. Finally, discuss how to iterate
through the stored attribute values in an array to retrieve the required values.
To end the discussion about attributes, use the review slide to recapitulate
the main concepts covered in the module.
Module14: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 Module14: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.
Module14: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 Module14: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
Module14: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 Module14: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.
[...]... of the predefined NET Framework attributes that the NET Framework runtime interprets automatically Module 14:Attributes 13 Defining Custom Attributes Topic Objective To introduce the topics covered in this section Lead-in You can define your own custom attributes Defining Custom Attribute Scope Defining an Attribute Class Processing a Custom Attribute Using Multiple Attributes *****************************ILLEGAL... constructor Delegate delegate Enum enum Event event Field field Interface interface Method method Module moduleModule 14: Attributes 15 (continued) Member name Attribute can be applied to Parameter parameter Property property ReturnValue return value Struct struct Assembly assembly All Any element Example of Using Custom Attributes To specify that the MyAttribute custom attribute can be applied only to methods,... method The parameter specifies whether to search the inheritance chain You can then iterate through the array to find the values of the attributes that you are interested in Module 14:Attributes 25 Iterating Through Attributes You can iterate through the array of attributes and examine the value of each one in turn In the following code, the only attribute of interest is DeveloperInfoAttribute, and... typeof(DeveloperInfoAttribute); if (typeInfo.IsDefined(devInfoAttrType, false)) { object [ ] attrs = typeInfo.GetCustomAttributes(devInfoAttrType, false); } Note You can use Intermediate Language Disassembler (ILDASM) to see these attributes inside the assembly 26 Module14:Attributes Lab 14.1: Defining and Using Attributes Topic Objective To introduce the lab Lead-in In this lab, you will use the predefined Conditional... 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 8 Module14:Attributes Visual Designer Component-Building Attributes Developers who build components... element on which it is applied 20 Module14:Attributes Using Multiple Attributes Topic Objective To describe how the same attribute can be applied multiple times to the same programming element Lead-in Depending upon the circumstances, it might be useful to use a custom attribute multiple times on the same element An element can have more than one attribute Define both attributes separately An element... Using Multiple Attributes You can apply more than one attribute to a programming element For example, the following code shows how you can tag the FinancialComponent class with two attributes: Transaction and DefaultProperty [Transaction(TransactionOption.Required)] [DefaultProperty("Balance")] public class FinancialComponent: System.Attribute { public long Balance { } } Module14:Attributes 21 Using... actually the abstract base class of the other “Info” types 24 Module14:Attributes Querying for Attribute Information Topic Objective To show how to use the GetCustomAttributes method Lead-in Once you have the MemberInfo for a class, you can query to find out attribute information for that class To retrieve attribute information: Use GetCustomAttributes to retrieve all attribute information as an array.. .Module 14:Attributes 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 7 COM Interoperability Attributes When using the attributes to provide interoperability with COM, the... metadata of their associated elements, and they provide mechanisms for a program to retrieve their values After completing this lesson, you will be able to: Define your own custom attributes Use your own custom attributes 14 Module14:Attributes Defining Custom Attribute Scope Topic Objective To describe the scope of a custom attribute Use the AttributeUsage tag to define scope Example Lead-in You need to .
iv Module 14: Attributes
Module Strategy
Use the following strategy to present this module:
Overview of Attributes
Begin by explaining that attributes. upon it.
2 Module 14: Attributes
Overview of Attributes
Introduction to Attributes
Applying Attributes
Common Predefined Attributes