Beruflich Dokumente
Kultur Dokumente
Delegates
.Net delegates are present as a reference type, and all delegates
inherit from the System.Delegate type.
Hence, technically, our prior definition that said 'a delegate is a
reference to a method' is not quite appropriate.
A delegate is a reference type derived from System.Delegate and
its instances can be used to call methods with matching
signatures.
Another important thing to note here is that since defining a
delegate means creating a new sub-type of System.Delegate, the
delegates can not be defined within a method (which is also true
for ordinary types).
A delegate in C# is similar to a function pointer in C or C++.
Using a delegate allows the programmer to encapsulate a
reference to a method inside a delegate object.
An interesting and useful property of a delegate is that it does not
know or care about the class of the object that it references.Any
object will do; all that matters is that the method's argument
types and return type should match the delegate's.
Example
// Declaration
public delegate void SimpleDelegate();
class Program
{
public static void MyFunc()
{
Console.WriteLine("I was called by delegate ...");
}
public static void Main()
{
// Instantiation
SimpleDelegate simpleDelegate = new
SimpleDelegate(MyFunc);
// Invocation
simpleDelegate();
Console.ReadLine();
Events
An Event is the way for a class to provide notifications to clients of
that class when some interesting things happen to an object
The most familiar use for events is in GUI. The class that
represent controls in the interface have events that are notified
when does something to the control (E.g. Click a Button)
An event is the out come of an action
There are two important terms with respect to the events are
Event Source and Event Receiver
The object that raises the event is called Event Source
The object that responds to the event is called event receiver
The communication channel between an Event Source and An
Event Receiver is Delegate
Conventions
Event Handlers in the .NET Framework return void and take two
parameters.
The first parameter is the source of the event; that is the
publishing object
The second parameter is an object derived from EventArgs
Raise Event
Invoke/Call
Method
Class Receiving Event
Event
Delegate
Invoke/Call
Delegate Target
Method
THANK YOU