Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 42 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
42
Dung lượng
856,93 KB
Nội dung
Contents
Overview 1
Overview of Attributes 2
Defining Custom Attributes 13
Retrieving Attribute Values 22
Demonstration: Custom Attributes 26
Lab 17: Defining and Using Attributes 27
Review 36
Module 17(Optional):
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, ActiveX, BizTalk, IntelliMirror, Jscript, MSDN, MS-DOS, MSN, PowerPoint,
Visual Basic, Visual C++, Visual C#, Visual Studio, Win32, Windows, Windows Media, and
Window NT 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.
Module17(Optional):Attributes iii
Instructor Notes
Teach this module if time permits. Module17 is a stand-alone module that is
not dependent upon any other module.
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 Microsoft PowerPoint
®
file 2349B_17.ppt.
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 the Microsoft Intermediate Language disassembler to
examine the metadata of an assembly.
Presentation:
60 Minutes
Lab:
45 Minutes
iv Module17(Optional):Attributes
Demonstration
This section provides demonstration procedures that will not fit in the margin
notes or are not appropriate for the student notes.
Use the debugger to step through the code while you point out features and ask
students what they think will happen next.
Custom Attributes
In this demonstration, you will show students how to declare and apply custom
attributes and how to use reflection to retrieve custom attribute metadata.
The code for this demonstration is contained in one project and is located in
<install folder>\Democode\Mod17.
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.
Module17(Optional):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 Microsoft
®
Visual C#
™
.NET 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
Microsoft Visual C# .NET.
Delivery Tip
Teach this module if time
permits. This is a stand-
alone module that is not
dependent upon any other
module.
2 Module17(Optional):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.
Module17(Optional):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 software development kit (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 Module17(Optional):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
Module17(Optional):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:
[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 Module17(Optional):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 documentation.
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.
SecurityPermissionAttributes Assembly,
Class, Struct,
Constructor,
Method
Allows security actions for
SecurityPermission to be
applied to code using
declarative security.
Topic Objective
To list some common
predefined attributes.
Lead-in
The .NET Framework
provides a large number of
predefined attributes.
[...]... predefined NET Framework attributes that the NET Framework runtime interprets automatically Module 17(Optional):Attributes 13 " Defining Custom Attributes Topic Objective To introduce the topics covered in this section ! Defining an Attribute Class ! Processing a Custom Attribute ! You can define your own custom attributes Defining Custom Attribute Scope ! Lead-in Using Multiple Attributes *****************************ILLEGAL... (typeInfo.IsDefined(devInfoAttrType, false)) { Object [ ] attrs = typeInfo.GetCustomAttributes(devInfoAttrType, false); } Note You can use the Microsoft Intermediate Language Disassembler to see these attributes inside the assembly 26 Module17(Optional):Attributes Demonstration: Custom Attributes Topic Objective This demonstration shows how to declare and apply custom attributes and how to use reflection to retrieve custom... type: MyAttribute Name Property: This is an example attribute associated! with the method MyMethod in MyClass1 member name: GetType has 0 custom attributes: member name: ctor has 0 custom attributes: Module17(Optional):Attributes 27 Lab 17: Defining and Using Attributes Topic Objective To introduce the lab Lead-in In this lab, you will use the predefined Conditional attribute, and then create and use... Constructor constructor Delegate delegate Enum enum Event event Field field Interface interface Method method Module moduleModule 17 (Optional):Attributes 15 (continued) Member name Attribute can be applied to Parameter parameter Property property ReturnValue return value Struct struct Example of Using Custom Attributes To specify that the MyAttribute custom attribute can be applied only to methods, use the... 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 17(Optional):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,... the Attribute suffix 20 Module17(Optional):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... 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: DeveloperInfo and DefaultProperty: [DeveloperInfo("Bert", Date="08-28-2001")] [DefaultProperty("Balance")] public class FinancialComponent: { public long Balance { } } Module17(Optional):Attributes 21 Using... abstract base class of the other “Info” types 24 Module17(Optional):Attributes Querying for Attribute Information Topic Objective To show how to use the GetCustomAttributes method ! To Retrieve Custom Attribute Information: # Lead-in Once you have the MemberInfo for a class, you can query to find out attribute information for that class Use GetCustomAttributes to retrieve all attribute information.. .Module 17(Optional):Attributes Delivery Tip Avoid getting into long conversations about COM, transactions, and interoperability because this is beyond the scope of this module This information is presented to show that the NET Framework is compatible with COM Tell students that COM and interoperability is covered in depth in Module 15, “Interoperating Between Managed... 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 Module17(Optional):Attributes Defining Custom Attribute Scope Topic Objective To describe the scope of a custom attribute ! Use the AttributeUsage Tag to Define Scope # Lead-in Example . owners.
Module 17 (Optional): Attributes iii
Instructor Notes
Teach this module if time permits. Module 17 is a stand-alone module that is. stand-
alone module that is not
dependent upon any other
module.
2 Module 17 (Optional): Attributes
"
""
" Overview of Attributes