Guide to the Language


Download 2 Mb.
Pdf ko'rish
bet70/78
Sana30.04.2023
Hajmi2 Mb.
#1414515
TuriGuide
1   ...   66   67   68   69   70   71   72   73   ...   78
Bog'liq
C sharp

 Generic Interfaces
Interfaces that are declared with type parameters become generic 
interfaces. Generic interfaces have the same two purposes as regular 
interfaces. They are either created to expose members of a class that 
will be used by other classes or to force a class to implement a specific 
functionality. When a generic interface is implemented, the type argument 
must be specified. The generic interface can be implemented by both 
generic and non-generic classes.
// Generic functionality interface
interface IGenericCollection
{
void store(T t);
}
// Non-generic class implementing generic interface
class Box : IGenericCollection
{
public int myBox;
public void store(int i) { myBox = i; }
}
// Generic class implementing generic interface
class GenericBox : IGenericCollection
{
public T myBox;
public void store(T t) { myBox = t; }
}
Chapter 28 GeneriCs


165
 Generic Delegates
A delegate can be defined with type parameters. As an example, the 
following generic delegate uses its type parameter to specify the referable 
method’s parameter. From this delegate type, a delegate object can be 
created that can refer to any void method that takes a single argument, 
regardless of its type.
class MyClass
{
public delegate void MyDelegate(T arg);
public void Print(string s)
{
System.Console.Write(s);
}
static void Main()
{
MyDelegate d = Print;
}
}
 Generic Events
Generic delegates can be used to define generic events. For example, 
instead of using the typical design pattern where the sender of the event is 
of the Object type, a type parameter can allow the sender’s actual type to 
be specified. This will make the argument strongly typed, which allows the 
compiler to enforce that the correct type is used for that argument.
delegate void MyDelegate(T sender, U eventArgs);
event MyDelegate myEvent;
Chapter 28 GeneriCs


166

Download 2 Mb.

Do'stlaringiz bilan baham:
1   ...   66   67   68   69   70   71   72   73   ...   78




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