BACS 387 - University of Northern Colorado

Download Report

Transcript BACS 387 - University of Northern Colorado

Events
Creation & Use








Refresh you memory concerning C# delegates.
Introduce multicast delegates.
Learn the basics of events and how they work.
Learn how to declare an event.
Learn about event standard usage.
Learn how to raise an event
Learn how to subscribe to an event.
Understand event code examples.
Last update: 7/21/2015
OO Programming
2

There are two general categories of class members in C#.
 Data members –store data associated with the class or instances
of the class.
 Function members – execute code and model the actions of the
real-world object that the class represents.

C# classes can have any number of data and function
members. They can come from any combination of 9
possible member types.
Data Members
Function Members
Fields √
Methods √
Operators ≈
Constants √
Properties√
Indexers √
Constructors √
Events
Destructors √
Last update: 7/21/2015
OO Programming
3
A delegate is an object that points to another
method (or list of methods) in the application.
 It allows you to pass the method as a parameter
to another method.
 So you can perform indirect invocation.
 A delegate object has 3 important pieces of
information:

 the address of the method that it calls
 the arguments of this method
 the return value of this method

Once created, a delegate dynamically invokes the
method(s) that it points to at runtime.
7/21/2015
OO Programming
4
public delegate int MathOp(int x, int y);
public class SimpleMath
{
public static int Add(int x, int y)
{ return x + y; }
public static int Sub(int x, int y)
{ return x – y; }
}
Create the delegate
Methods that the
delegate will point
to
class Program
Create delegate variables
{
Static void Main()
{
MathOp myOp = new MathOp(SmpleMath.Add);
MathOp myOp2 = new MathOp(SimpleMath.Sub);
Console.WriteLine(“10 + 10 is {0}”, myOp(10,10));
Console.WriteLine(“10 – 5 is {0}”, myOp2(10,5));
}
}
Call the delegate using
the variables
7/21/2015
OO Programming
5
public delegate void Greetings(string s);
Create the delegate
public static void Hello(string s)
{ Console.WriteLine(“Hello, {0}”,s); }
public static void Bye(string s)
{ Console.WriteLine(“Bye, {0}”,s); }
Methods that the
delegate will point
to
public static void GreetMethod (Greetings g, string name)
{
Console.WriteLine(“The greeting is:”);
g(name);
method that uses the
}
public Static void Main()
{
Greetings firstPerson;
Greetings secondPerson;
firstPerson = new Greetings(Hello);
secondPerson = new Greetings(Bye);
GreetMethod(firstPerson, “Jim”);
GreetMethod(secondPerson, “Sue”);
}
7/21/2015
OO Programming
delegate
Create delegate variables
Call the delegate using
the variables
6
Delegates in C# have the ability to multicast.
This means that a delegate object can maintain a list
of methods to call, rather than a single method.
 When you want to add multiple methods to a
delegate object, you use the += overload operator.
myDelegate += aNewMethod;
 This is called registering methods to the delegate.
 Similarly, you may want to remove methods from a
delegate. There is also special syntax for this.


myDelegate -= removeMethod;
Last update: 7/21/2015
OO Programming
7





This is important because it illustrates that you must
manage delegates by hand with custom code.
If you forget to register or unregister methods from the
delegate’s invocation list, then your delegates will be
out of sync with what you want the program to do.
There is also a problem if you forget to declare local
variables in the delegated method as private.
Public method variables can be manipulated by external
entities which opens up a security concern.
All this can be fixed by using events (which are created
with the event keyword).
Last update: 7/21/2015
OO Programming
8





Events similar to delegates because they are pointers to
methods that are invoked under certain circumstances.
Events are also similar to exceptions in that they are
raised (thrown) by objects.
You can supply code that acts on these events. The unit
that holds this code is called an event handler.
You must subscribe to them (i.e., register).
Events are superior to delegates because they
automatically handle all the registering and
unregistering details along with any private member
variables for your delegate types.
Last update: 7/21/2015
OO Programming
9





You can add (subscribe) many event handlers to a
specific event.
All of the event handlers are called when the event
is raised.
These could include handlers in the class where the
event is defined and handlers from other classes.
Event handlers are really functions. They must
match the return type and parameters required by
the event.
These details are specified by a delegate.
Last update: 7/21/2015
OO Programming
10
To declare an event, you use a delegate.
An event provides a way for a class’s clients to
dictate methods that should execute when an event
occurs.
 The clients identify methods to execute by providing
delegates.
 When an event occurs, any delegate that a client has
given or passed to the event is invoked.
 Once invoked, it runs like a normal function
accepting its parameters and performing its actions.


Last update: 7/21/2015
OO Programming
11

.NET provides a default handler that does not require a
user-define delegate. It is called EventHandler: You
should use this in your programs
public event EventHandler MyFinalEvent;

You can also declare an event by hand by using the
following syntax:
public event MyEventHandler MyEvent;

You can declare more than one event in a single
statement as follows:
public event MyHandler MyEvent1, MyEvent2;

You can also declare an event as static as follows:
public static event MyHandler2 MyNewEvent;
Last update: 7/21/2015
OO Programming
12
All .NET programmers should adhere to the standard
event usage rules as often as possible.
 These rules say that you use the build-in
EventHandler delegate type. For example:

public delegate void EventHandler(object sender, EventArgs e);
The first parameter holds a reference to the object
that raised the event.
 The second parameter holds state information about
whatever type is appropriate for the application.
 The return type is void.

Last update: 7/21/2015
OO Programming
13
The event member itself merely holds the event
handlers that will be invoked.
 Nothing happens with them until an event is raised.
 You should check if the event is null before invoking
it. This avoids the problem of invoking an event
with no handlers. The syntax to do this is:

If (MyEvent != null)
MyEvent(source, args);

Raising the event is like invoking a function. Use the
name of the event and put parameters in the () that
follow.
Last update: 7/21/2015
OO Programming
14


Subscribing to an event adds the event handler to the
event.
You use the += operator to do this.
Door1.Opened += ca.DoorHandler;
Door2.Opened += ClassA.DoorHandler;
Door3.Opened += new EventHandler(ca.DoorHandler);



The first example uses method reference form on an
instance method.
The second example uses method reference form on a
static method.
The last example uses delegate form on an instance
method.
Last update: 7/21/2015
OO Programming
15
Delegates are objects that point to one or more methods
that can be indirectly invoked.
 Delegates can invoke many methods from a single event.
 Events are similar to delegates in that they invoke code
when specific conditions occur.
 Events work with delegates and are actually a short-cut
method to let C# handle some of the low-level details for
you.
 There is a specific syntax needed to declare, raise, and
subscribe to events.
 Whenever possible, you should use the standard usage event
handler defined by EventHandler.

Last update: 7/21/2015
OO Programming
16