logo
CSharp_Prog_Guide

Использование словаря для хранения экземпляров событий

Одно из применений accessor-declarations заключается в предоставлении доступа к большому числу событий без выделения поля для каждого события, но с использованием словаря для хранения экземпляров событий. Это полезно только в том случае, когда имеется много событий, но ожидается, что большинство из них не будут реализованы.

Пример

-------

internal void RaiseEvent1(int i)

{

EventHandler1 handler1;

if (null != (handler1 = (EventHandler1)eventTable["Event1"]))

{

handler1(i);

}

}

internal void RaiseEvent2(string s)

{

EventHandler2 handler2;

if (null != (handler2 = (EventHandler2)eventTable["Event2"]))

{

handler2(s);

}

}

}

public class TestClass

{

public static void Delegate1Method(int i)

{

System.Console.WriteLine(i);

}

public static void Delegate2Method(string s)

{

System.Console.WriteLine(s);

}

static void Main()

{

PropertyEventsSample p = new PropertyEventsSample();

p.Event1 += new EventHandler1(TestClass.Delegate1Method);

p.Event1 += new EventHandler1(TestClass.Delegate1Method);

p.Event1 -= new EventHandler1(TestClass.Delegate1Method);

p.RaiseEvent1(2);

p.Event2 += new EventHandler2(TestClass.Delegate2Method);

p.Event2 += new EventHandler2(TestClass.Delegate2Method);

p.Event2 -= new EventHandler2(TestClass.Delegate2Method);

p.RaiseEvent2("TestString");

Console.ReadLine();

}

}

2

TestString

-----

Generics

Generics were added to version 2.0 of the C# language and the common language runtime (CLR). Generics introduce to the .NET Framework the concept of type parameters, which make it possible to design classes and methods that defer the specification of one or more types until the class or method is declared and instantiated by client code. For example, by using a generic type parameter T you can write a single class that other client code can use without incurring the cost or risk of runtime casts or boxing operations, as shown here:

// Declare the generic class.

public class GenericList<T>

{

void Add(T input) { }

}

class TestGenericList

{

private class ExampleClass { }

static void Main()

{

// Declare a list of type int.

GenericList<int> list1 = new GenericList<int>();

// Declare a list of type string.

GenericList<string> list2 = new GenericList<string>();

// Declare a list of type ExampleClass.

GenericList<ExampleClass> list3 = new GenericList<ExampleClass>();

}

}

Generics Overview