Sie sind auf Seite 1von 61

Course Outline

1 Course Outline

Course Outline

Introduction to Software Development with Visual


Studio 2008
Introduction to the .NET Framework
Language Specific Concepts

Introduction

Introduction to Software Development mit Visual


Studio 2008
Visual Studio Solutions
C# Project Templates
Help System
Class Designer
Code Snippets
Refactoring Tools

Page 1
Course Outline

Introduction to the .NET Framework


Basic Concepts: Intermediate Language (IL), Common
Type System (CTS), Common Language Runtime
(CLR)
.NET Components: Private and Global Assemblies,
Assembly References, Namespaces, .NET Cross
Language Interoperability
.NET Class Library (Overview), Namespaces,
.NET versions

Language Specific Concepts

Reference and Value Types


User Defined Data Types: Class, Struct,
Enumeration
Constructor, Destructor, Garbage Collector
Properties and Indexer
Overloading and Overriding Methods: Early vs.
Late Binding
Interfaces: Marker Interfaces, Multiple
Inheritance, Multiple Implementation, Extracting
Interfaces
Standard Interfaces (e.g. ICloneable,

Page 2
Course Outline

.NET Specific Concepts

Delegates and Events


Asynchronous Programming Model
Generic Data Types and Collections
Serialization
Instrumentation (Event Logging, Debugging,
Tracing, Performance Monitoring)
Globalization
Application Domains and Reflection
Language Extensions of .NET 3.5, Lambda
Expressions

Page 3
Object Oriented Techniques

2 Object Oriented Techniques


2.1 Classes and Objects

Classes and Objects

What Is a Class?
What Is an Object?
Comparing Classes to Structs
Abstraction

What Is a Class?

For the object-oriented programmer…


A named syntactic construct that describes
common behavior and attributes
A data structure that includes both data and
functions

Page 4
Object Oriented Techniques

What Is an Object?

An object is an instance of a class


Objects exhibit:
Identity: Objects are distinguishable from one
another
Behavior: Objects can perform tasks
State: Objects store information

Comparing Classes to Structs

A struct is a blueprint for a value


No identity, accessible state, no added behavior
A class is a blueprint for an object
Identity, inaccessible state, added behavior

Page 5
Object Oriented Techniques

Abstraction

Abstraction is selective ignorance


Decide what is important and what is not
Focus and depend on what is important
Ignore and do not depend on what is unimportant
Use encapsulation to enforce an abstraction

Using Encapsulation

Combining Data and Methods


Controlling Access Visibility
Why Encapsulate?
Object Data
Using Static Data
Using Static Methods

Page 6
Object Oriented Techniques

Combining Data and Methods

Combine the data and methods in a single capsule


The capsule boundary forms an inside and an outside

Controlling Access Visibility

Methods are public, accessible from the outside


Data is private, accessible only from the inside

Page 7
Object Oriented Techniques

Object Data

Object data describes information for individual


objects
For example, each bank account has its own
balance. If two accounts have the same balance, it
is only a coincidence.

Using Static Data

Static data describes information for all objects


of a class
For example, suppose all accounts share the same
interest rate. Storing the interest rate in every account
would be a bad idea. Why?

Page 8
Object Oriented Techniques

Using Static Methods

Static methods can only access static data


A static method is called on the class, not the
object

C# and Object Orientation

Hello, World Revisited


Defining Simple Classes
Instantiating New Objects
Using the this Operator
Creating Nested Classes
Accessing Nested Classes

Page 9
Object Oriented Techniques

Defining Simple Classes

Data and methods together inside a class


Methods are public, data is private

""

""

##
##

Instantiating New Objects

Declaring a class variable does not create an object


Use the new operator to create an object

!!
"
$ "
""

## $$
$$
%% ##
%% &&&&&&"
&&&&&&"

Page 10
Object Oriented Techniques

Using the this Keyword

The this keyword refers to the object used to call the


method
Useful when identifiers from different scopes
clash

'' ((

##
! ""

Creating Nested Classes

Classes can be nested inside other classes

!!

""

%% ##

%%

&& ""

Page 11
Object Oriented Techniques

Accessing Nested Classes

Nested classes can also be declared as public or


private

""
## (( ))
!!
""

(( ))

Defining Object-Oriented Systems

Inheritance
Class Hierarchies
Single and Multiple Inheritance
Polymorphism
Abstract Base Classes
Interfaces
Early and Late Binding

Page 12
Object Oriented Techniques

Inheritance

Inheritance specifies an “is a kind of" relationship


Inheritance is a class relationship
New classes specialize existing classes

$ %

&" % !! # '
"" ( "

Class Hierarchies

Classes related by inheritance form class hierarchies

" ))
))

&& '' " && ''


))

** "
**

Page 13
Object Oriented Techniques

Single and Multiple Inheritance

Single inheritance: deriving from one base class


Multiple inheritance: deriving from two or more base
classes

&& '' ))

&& ''
**

! ' # $

Polymorphism

The method name resides in the base class


The method implementations reside in the
derived classes

&& '' ))
""
++ ,, -- ""

$$ **

++ ,, -- ++ ,, --

Page 14
Object Oriented Techniques

Abstract Base Classes

Some classes exist solely to be derived from


It makes no sense to create instances of these
classes
These classes are abstract
++
&& '' ))
.. //
++

$$ **
00 11 00 11

Interfaces

Interfaces contain only operations, not


implementation

)) 22 '' "" 33
00 11 ++
33

)) "" 33
&& '' )) ++
.. // 33

)) "" "" 33
** ++
00 11 33

Page 15
Object Oriented Techniques

Early and Late Binding

Normal method calls are resolved at compile time


Polymorphic method calls are resolved at run time

))
00 11

++ ,, -- 4 '

**
00 11

++ ,, -- 5 '

2.2 Using Reference Types

Using Reference-Type Variables

Comparing Value Types to Reference Types


Declaring and Releasing Reference Variables
Invalid References
Comparing Values and Comparing References
Multiple References to the Same Object
Using References as Method Parameters

Page 16
Object Oriented Techniques

Comparing Value Types to Reference Types

Value types )
The variable
contains the
value directly #
"
Examples:
char, int
## ,-
,- ,,
## *+
*+ '' ((

%% &&

Declaring and Releasing Reference Variables

Declaring reference variables

66
66 ,-,-
6 63(3( 7 736368 8
'' ** ++ && %% &&
6 63 3 9 93838

)
$$ ##

'' ** ++ && %% &&

Page 17
Object Oriented Techniques

Invalid References

If you have invalid references


You cannot access members or variables
Invalid references at compile time
Compiler detects use of uninitialized references
Invalid references at run time
System will generate an exception error

Comparing Values and Comparing References

Comparing value types


== and != compare values
Comparing reference types
== and != compare the references, not the values

'' ++ ,, && ,,

'' ++ ,, && ,,

Page 18
Object Oriented Techniques

Multiple References to the Same Object

Two references can refer to the same object


Two ways to access the same object for read/write

+ ''
&& -- .. **
& ''
$#
$#
++
$$ .. ## ++ // $$ %% ## 00 11
++ ## $$
22 33 $$ .. 44 ,, 55 ,, 44 $$ %%
22 33 ++ .. 44 ,, 55 ,, 44 ++ %%

Using References as Method Parameters


References can be used as parameters
When passed by value, data being referenced may
be changed
&& -- -- %%
''
!! 22 %6
%6

.44
.44 %44
%44

.. ## ++ %% ## //
!! 22 %6
''
%6
22 33 .. 44 ,, 55 ,, 44 %%

Page 19
Object Oriented Techniques

Using Common Reference Types

Exception Class
String Class
Common String Methods, Operators, and Properties
String Comparisons
String Comparison Operators

Exception Class

Exception is a class
Exception objects are used to raise exceptions
Create an Exception object by using new
Throw the object by using throw
Exception types are subclasses of Exception

Page 20
Object Oriented Techniques

String Class

Multiple character Unicode data


Shorthand for System.String
Immutable

#
# ,-
,- ,,

789
789 #
#:::
: ;;
;; 22 <<

Common String Methods, Operators, and


Properties

Brackets
Insert method
Length property
Copy method
Concat method
Trim method
ToUpper and ToLower methods

Page 21
Object Oriented Techniques

String Comparisons

Equals method
Value comparison
Compare method
More comparisons
Case-insensitive option
Dictionary ordering
Locale-specific compare options

String Comparison Operators

The == and != operators are overloaded for strings


They are equivalent to String.Equals and
!String.Equals

## ,, ,,
## ,, ,,
== ##
## ;;
;; >>

Page 22
Object Oriented Techniques

The Object Hierarchy

The object Type


Common Methods
Reflection

The object Type

Synonym for System.Object


Base class for all classes

11

## // 00

## //

Page 23
Object Oriented Techniques

Common Methods

Common methods for all reference types


ToString method
Equals method
GetType method
Finalize method

Reflection

You can query the type of an object


System.Reflection namespace
The typeof operator returns a type object
Compile-time classes only
GetType method in System.Object
Run-time class information

Page 24
Object Oriented Techniques

Data Conversions

Converting Value Types


Parent/Child Conversions
The is Operator
The as Operator
Conversions and the object Type
Conversions and Interfaces
Boxing and Unboxing

Converting Value Types

Implicit conversions
Explicit conversions
Cast operator
Exceptions
System.Convert class
Handles the conversions internally

Page 25
Object Oriented Techniques

Parent/Child Conversions

Conversion to parent class reference


Implicit or explicit
Always succeeds
Can always assign to object
Conversion to child class reference
Explicit casting required
Will check that the reference is of the correct type
Will raise InvalidCastException if not

The is Operator

Returns true if a conversion can be made

==
## ;;
;; '' ==

22 33 ,(
,( ,,

Page 26
Object Oriented Techniques

The as Operator

Converts between reference types, like cast


On error
Returns null
Does not raise an exception

## ;;
;; 22

== ##
##
22 33 ,(
,( ,,

Conversions and the object Type

The object type is the base for all classes


Any reference can be assigned to object
Any object variable can be assigned to any reference
With appropriate type conversion and checks
The object type and is operator

?? ..
.. ## ## ..
.. ## ?? ## ..
.. ## ??

Page 27
Object Oriented Techniques

Conversion and Interfaces

An interface can only be used to access its own


members
Other methods and variables of the class are not
accessible through the interface

Boxing and Unboxing

Unified type system


Boxing
Unboxing
Calling object methods on value types

## $+/
$+/
?? .. ++ && -- ## ..
.. ##

'' ++ && --

Page 28
Object Oriented Techniques

2.3 Inheritance

Deriving Classes

Extending Base Classes


Accessing Base Class Members
Calling Base Class Constructors

Extending Base Classes

Syntax for deriving a class from a base class

«« 22

22 @@
00
«« 22
00

A derived class inherits most elements of its base class


A derived class cannot be more accessible than its base
class

Page 29
Object Oriented Techniques

Accessing Base Class Members

AA

BB
22 @@

((

Inherited protected members are implicitly protected in the derived


class
Methods of a derived class can access only their inherited protected
members
Protected access modifiers cannot be used in a struct

Calling Base Class Constructors

Constructor declarations must use the base keyword

22 @@

22 @@

A private base class constructor cannot be accessed by a derived


class
Use the base keyword to qualify identifier scope

Page 30
Object Oriented Techniques

Implementing Methods

Defining Virtual Methods


Working with Virtual Methods
Overriding Methods
Working with Override Methods
Using new to Hide Methods
Working with the new Keyword
Practice: Implementing Methods
Quiz: Spot the Bugs

Defining Virtual Methods

Syntax: Declare as virtual

33 ((

## "" ((

Virtual methods are polymorphic

Page 31
Object Oriented Techniques

Working with Virtual Methods

To use virtual methods:


You cannot declare virtual methods as static
You cannot declare virtual methods as private

Overriding Methods

Syntax: Use the override keyword

((

22 @@

## ((

Page 32
Object Oriented Techniques

Working with Override Methods


3

33 ((
((

22 @@

## 33 ((
## ((

3
3 /
3

Using new to Hide Methods

Syntax: Use the new keyword to hide a method

33 ((

22 @@

33 ((

Page 33
Object Oriented Techniques

Working with the new Keyword

Hide both virtual and non-virtual methods

33 ((
((

22 @@

33 ((
((

Resolve name clashes in code


Hide methods that have identical signatures

Practice: Implementing Methods

"" 22 ,, ,,

@@
"" 22 ,, ,,

2@
2@
"" 22 ,2,
,2,

@@ 22
"" 22 ,, ,,
""
## 22 ## ## ##
"" "" "" ""

Page 34
Object Oriented Techniques

Using Sealed Classes


You cannot derive from a sealed class
You can use sealed classes for optimizing operations at
run time
Many .NET Framework classes are sealed: String,
StringBuilder, and so on
Syntax: Use the sealed keyword
'%
'%
''

""
BB %'
%' @@ ''

Using Interfaces

Declaring Interfaces
Implementing Multiple Interfaces
Implementing Interface Methods
Implementing Interface Methods Explicitly
Quiz: Spot the Bugs

Page 35
Object Oriented Techniques

Declaring Interfaces

Syntax: Use the interface keyword to declare methods


$$
99$:
$:

'' CC
$$
44 22
33 ((
(( 55 66 77 88
66 77 88

66 66

Implementing Multiple Interfaces


A class can implement zero or more interfaces
== CC
$$ $!$!
(( 44 22 44 22
== C6
C6
C6
C6
@@ (( %% )) **
44 22

An interface can extend zero or more interfaces


A class can be more accessible than its base interfaces
An interface cannot be more accessible than its base interfaces
A class must implement all inherited interface methods

Page 36
Object Oriented Techniques

Implementing Interface Methods

The implementing method must be the same as the


interface method
The implementing method can be virtual or non-
virtual

@@ CC 55 C6
C6 ##
##
(( ##
##

C6
C6

Implementing Interface Methods Explicitly


Use the fully qualified interface method name
@@ (( %% 55 **

(( %% ((

** C6
C6

Restrictions of explicit interface method implementation


You can only access methods through the interface
You cannot declare methods as virtual
You cannot specify an access modifier

Page 37
Object Oriented Techniques

Using Abstract Classes

Declaring Abstract Classes


Using Abstract Classes in a Class Hierarchy
Comparing Abstract Classes to Interfaces
Implementing Abstract Methods
Working with Abstract Methods
Quiz: Spot the Bugs

Declaring Abstract Classes

Use the abstract keyword

;; <<
""

Page 38
Object Oriented Techniques

Using Abstract Classes in a Class Hierarchy

/ +
== CC
(( 44 22

@@ CC
CC ((
;; <<

22 @@ 00 ==

DD %% @@ 44 22 44 22

Using Abstract Classes in a Class Hierarchy


(continued)
/ &
== CC
(( 44 22

((
;; <<

22 @@ 55 CC 00 ==

DD %% @@ 55 CC 44 22 44 22

Page 39
Object Oriented Techniques

Comparing Abstract Classes to Interfaces

Similarities
Neither can be instantiated
Neither can be sealed
Differences
Interfaces cannot contain any implementation
Interfaces cannot declare non-public members
Interfaces cannot extend non-interfaces

Implementing Abstract Methods

Syntax: Use the abstract keyword

## "" ((
33

22 @@

((
33

Only abstract classes can declare abstract methods


Abstract methods cannot contain a method body

Page 40
Object Oriented Techniques

Working with Abstract Methods

Abstract methods are virtual


Override methods can override abstract methods in
further derived classes
Abstract methods can override base class methods
declared as virtual
Abstract methods can override base class methods
declared as override

2.4 Operators

Operators and Methods

Using methods
Reduces clarity
Increases risk of errors, both syntactic and semantic
%C
%C 66 $$ ## CC %C
%C 66 +5
+5
CC CC %C
%C 66 /5
/5
%C
%C 66 ** 55 //
//

Using operators
Makes expressions clear

%C
%C 66 $$ ## %C
%C 66 ++ 44 %C
%C 66 // 44 %C
%C 66 ** 44 //
//

Page 41
Object Oriented Techniques

Predefined C# Operators

1 0
Arithmetic Member access

Logical (Boolean Indexing


and bitwise)
String concatenation Cast

Increment and decrement Conditional

Shift Delegate concatenation


and removal
Relational Object creation

Assignment Type information

Overflow exception Indirection and address


control

Operator Overloading

Introduction to Operator Overloading


Overloading Relational Operators
Overloading Logical Operators
Overloading Conversion Operators
Overloading Operators Multiple Times

Page 42
Object Oriented Techniques

Introduction to Operator Overloading

Operator overloading
Define your own operators only when appropriate
Operator syntax
Operatorop, where op is the operator being
overloaded
Example
"" (( $$ ++ (( $$ )) (( $$
,,
-- "" .. "" ++ "" //
00 "" .. $$ "" ++ $$ "" //
"" (( $$ -- "" )) 00 "" //
11

Overloading Relational Operators

Relational operators must be paired


< and >
<= and >=
== and !=
Override the Equals method if overloading == and !=
Override the GetHashCode method if overriding
equals method

Page 43
Object Oriented Techniques

Overloading Logical Operators

Operators && and || cannot be overloaded directly


They are evaluated in terms of &, |, true, and
false, which can be overloaded
x && y is evaluated as T.false(x) ? x : T.&(x, y)
x || y is evaluated as T.true(x) ? x : T.|(x, y)

Overloading Conversion Operators

Overloaded conversion operators

.. ==

.. == $$

$$

If a class defines a string conversion operator


The class should override ToString

Page 44
Object Oriented Techniques

Overloading Operators Multiple Times

The same operator can be overloaded multiple times

44 $5
$5

44 $5
$5 ==

<< $5
$5

<< $5
$5 ==

2.5 Attributes

Overview of Attributes

Introduction to Attributes
Applying Attributes
Common Predefined Attributes
Using the Conditional Attribute
Using the DllImport Attribute
Using the Transaction Attribute

Page 45
Object Oriented Techniques

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

Applying Attributes

Syntax: Use Square Brackets to Specify an Attribute

77 EE 99

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

Page 46
Object Oriented Techniques

Common Predefined Attributes

.NET Provides Many Predefined Attributes


General attributes
COM interoperability attributes
Transaction handling attributes
Visual designer component-building attributes

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
"%2
"%2

72
72 ,, FF G))C(),
G))C(), 99
"%"
"%"

Restrictions on Methods
Must have return type of void
Must not be declared as override
Must not be from an inherited interface

Page 47
Object Oriented Techniques

Using the DllImport Attribute

With the DllImport Attribute, You Can:


Invoke unmanaged code in DLLs from a C#
environment
Tag an external method to show that it resides in
an unmanaged DLL
77 CC ,"%
,"% 33
33 ,5
,5 FF %!%! #H"%B
#H"%B ,, 99
.. "%B
"%B $$

"%2
"%2

## "%B
"%B ,-
,- GG 22 ,,

Using the Transaction Attribute

To Manage Transactions in COM+


Specify that your component be included when a
transaction commit is requested
Use a Transaction attribute on the class that
implements the component

FF ''

77 AA >> II 99
"%
"% 22 @@ '' 22

Page 48
Object Oriented Techniques

Defining Custom Attributes

Defining Custom Attribute Scope


Defining an Attribute Class
Processing a Custom Attribute
Using Multiple Attributes

Defining Custom Attribute Scope

Use the AttributeUsage Tag to Define Scope


Example

77 GG "" 99
"%
"% @@ '%
'%

Use the Bitwise “or” Operator (|) to Specify


Multiple Elements
Example
77 GG 22 JJ '' 99
"%
"% @@ '%
'%

Page 49
Object Oriented Techniques

Defining an Attribute Class

Deriving an Attribute Class


All attribute classes must derive from
System.Attribute, directly or indirectly
Suffix name of attribute class with “Attribute”
Components of an Attribute Class
Define a public constructor for the attribute class
whose arguments are the required positional
parameters
Use non-static public read-write properties for
optional named parameters

Processing a Custom Attribute

The Compilation Process


1. Searches for the Attribute Class
2. Checks the Scope of the Attribute
3. Checks for a Constructor in the Attribute
4. Creates an Instance of the Object
5. Checks for a Named Parameter
6. Sets Field or Property to Named Parameter Value
7. Saves Current State of Attribute Class

Page 50
Object Oriented Techniques

Using Multiple Attributes

An Element Can Have More Than One Attribute


Define both attributes separately
An Element Can Have More Than One Instance of
The Same Attribute
Use AllowMultiple = true

Retrieving Attribute Values

Examining Class Metadata


Querying for Attribute Information

Page 51
Object Oriented Techniques

Examining Class Metadata

To Query Class Metadata Information:


Use the MemberInfo class in System.Reflection
Populate a MemberInfo array by using the method
System.Type.GetMembers
Create a System.Type object by using the
typeof operator
Example
'%
'% >> == "" CC == 77 99 CC == %%
CC == %% ## %% == "%2
"%2 )) ""

Querying for Attribute Information

To Retrieve Custom Attribute Information:


Use GetCustomAttributes to retrieve all attribute
information as an array

'%
'% >> == "" CC == %% CC ==
%% CC == ## %% == "%2
"%2
?? 77 99 ## %% CC == )) 22 ==

Iterate through the array and examine the values of


each element in the array
Use the IsDefined method to determine whether a
particular attribute has been defined for a class

Page 52
Object Oriented Techniques

2.3 Delegates and Events

Overview

Delegates
Multicast Delegates
Events
When to Use Delegates, Events, and Interfaces

Delegates

Delegate Scenario
Declaring a Delegate
Instantiating a Delegate
Calling a Delegate

Page 53
Object Oriented Techniques

Delegate Scenario

+ >0
# 1
?
1 @

5 1
1 @

& >1 @

1 @ 0

- > ? % >1 @ 0
1 @ 0 ?

Declaring a Delegate

A Delegate Declaration Defines a Type That


Encapsulates a Method with a Particular Set of
Arguments and Return Type

;;
;; ==
;;
;; == %% %%
"%
"%

Page 54
Object Oriented Techniques

Instantiating a Delegate

A Delegate Object Is Created with the new Operator


Delegate Objects Are Immutable

;;
;; --
;;
;; "%2
"%2
"%
"% ## "%
"% "%2
"%2 --

;;
;;
;;
;; "" ??
"%2
"%2 ## "%2
"%2
"%
"% ## "%
"% ""

Calling a Delegate

Use a Statement Containing:


The name of the delegate object
Followed by the parenthesized arguments to be
passed to the delegate

;;
;;
;;
;; 55 == "%2
"%2
;;
;; -- ,, ,,

,, ,,

Page 55
Object Oriented Techniques

Multicast Delegates

Multicast Delegate Scenario


Single vs. Multicast Delegates
Creating and Invoking Multicast Delegates
C# Language-Specific Syntax
Delegate Details

Multicast Delegate Scenario


% >1 @ 0
+ >0 +?
# 1
?
5 + 1
1 @
5 & 1

1 @ 1 @ 0

1 @ 0
& >1 @
- > +
+ +? 1 @ 0
. >1 @ 0
$
&?
++

A > & && * > &


&? 1 @ 0

Page 56
Object Oriented Techniques

Single vs. Multicast Delegates


All Delegates Have an Invocation List of Methods That Are
Executed When Their Invoke Method is Called
Single-Cast Delegates: Derived Directly From
System.MulticastDelegate
Invocation list contains only one method
Multicast Delegates: Derived from System.MulticastDelegate
Invocation list may contain multiple methods
Multicast delegates contain two static methods to add and
remove references from invocation list: Combine and
Remove
Use GetInvocationList to Obtain an Invocation List as an Array
of Delegate References
Use a Delegate’s Target and Method Properties to Determine:
Which object will receive the callback
Which method will be called

Creating and Invoking Multicast Delegates

;;
;; ==
## "%
"% 22 55

;;
;; == ==
## "%
"% >> 55

;;
;; CC ::
;;
;; ..
79
79 33 ## )) CC 33
== ## 88 KK 33 33 44
44
== 33 77 99 L# B
L# B $$
"%
"% 33 77 99

Page 57
Object Oriented Techniques

C# Language-Specific Syntax

C# Delegates That Return Void Are Multicast


Delegates
In C#, Use the + and - Operators to Add and Remove
Invocation List Entries
Less verbose than Combine and Remove
methods
"%
"% 55 55 55
## "%
"% BB
## "%
"%
## 44 ;;
;; 22
## << ;;
;; >> ==
4#
4# ;;
;; ::
<#
<# ;;
;; >> == ::

Delegate Details

A Delegate Declaration Causes the Compiler to


Generate a New Class

;;
;; "%
"% //

"%
"% // @@ '%
'% ""
"%
"% // ?? ?5
?5 == ==
@@ ?5
?5 == ;;
;;

CC ;;
;;

Page 58
Object Oriented Techniques

Events

Event Scenario
Declaring an Event
Connecting to an Event
Raising an Event
.NET Framework Guidelines

Declaring an Event

Declare the Delegate Type for the Event


Declare the Event
Like the field of delegate type preceded by an event
keyword
;;
;; "" 22
"" 22 FF --

""

;;
;; "" 22
"" 22 FF --
"" 22
;;
;;

Page 59
Object Oriented Techniques

Connecting to an Event

Connect by Combining Delegates


Disconnect by Removing Delegates
;;
;; 22 MM "" 22
"" 22 ;;
;;

;;
;;

;;
;; 22 "" 22
"" "" 22 4#
4#
"" 22 FF -- "" 22

;;
;; 22 "" 22
"" "" 22 <#
<#
"" 22 FF -- "" 22

Raising an Event

Check Whether Any Clients Have Connected to


This Event
If the event field is null, there are no clients
Raise the Event by Invoking the Event’s
Delegate

== "" 2
2 L#
L#
"
" 2
2

Page 60
Object Oriented Techniques

.NET Framework Guidelines

Name Events with a Verb and Use Pascal Casing


Use “Raise” for Events, Instead of “Fire”
Event Argument Classes Extend System.EventArgs
Event Delegates Return Void and Have Two
Arguments
Use a Protected Virtual Method to Raise Each Event
'' BB FF @@ FF ;;
;;

'' BB FF --
?? 55 '' BB FF

'' BB FF -- '' BB

When to Use Delegates, Events, and Interfaces

Use a Delegate If:


You basically want a C-style function pointer
You want single callback invocation
The callback should be registered in the call or at construction time,
not through an add method call
Use Events If:
Client signs up for the callback function through an add method call
More than one object will care
You want end users to be able to easily add a listener to the
notification in the visual designer
Use an Interface If:
The callback function entails complex behavior,
such as multiple methods

Page 61

Das könnte Ihnen auch gefallen