Guide to the Language


Download 2 Mb.
Pdf ko'rish
bet67/78
Sana30.04.2023
Hajmi2 Mb.
#1414515
TuriGuide
1   ...   63   64   65   66   67   68   69   70   ...   78
Bog'liq
C sharp

 Subscribing to Events
The Publisher and Subscriber classes are now complete. To demonstrate 
their use, a Main method is added where objects of the Publisher and 
Subscriber classes are created. In order to register the handler in the 
Subscriber object to the event in the Publisher object, the event handler 
is added to the event as if it were a delegate. Unlike a delegate, however, 
the event may not be called directly from outside its containing class. 
Instead, the event can only be raised by the Publisher class, which in this 
case occurs when an item is added to that object.
class MyApp
{
static void Main()
{
Subscriber s = new Subscriber();
Publisher p = new Publisher();
p.Added += s.AddedEventHandler;
p.Add(10); // "AddEvent occurred"
}
}
Chapter 27 events


159
© Mikael Olsson 2020 
M. Olsson, C# 8 Quick Syntax Reference
https://doi.org/10.1007/978-1-4842-5577-3_28
CHAPTER 28
Generics
Generics refer to the use of type parameters, which provide a way to design 
code templates that can operate with different data types. Specifically, it 
is possible to create generic methods, classes, interfaces, delegates, and 
events.
 Generic Methods
In the following example, there is a method that swaps two integer 
arguments.
static void Swap(ref int a, ref int b)
{
int temp = a;
a = b;
b = temp;
}
To make this into a generic method that can work with any data type,
a type parameter first needs to be added after the method’s name, 
enclosed between angle brackets. The naming convention for type 
parameters is that they should start with a capital T and then have each 
word that describes the parameter initially capitalized. In cases such as 
this however, where a descriptive name would not add much value, it is 
common to simply name the parameter with a capital T.


160
static void Swap(ref int a, ref int b)
{
int temp = a;
a = b;
b = temp;
}
The type parameter can now be used as any other type inside the 
method, and so the second thing that needs to be done to complete the 
generic method is to replace the data type that will be made generic with 
the type parameter.
static void Swap(ref T a, ref T b)
{
T temp = a;
a = b;
b = temp;
}

Download 2 Mb.

Do'stlaringiz bilan baham:
1   ...   63   64   65   66   67   68   69   70   ...   78




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling