How to: Use a Dictionary to Store Event Instances 


Мы поможем в написании ваших работ!



ЗНАЕТЕ ЛИ ВЫ?

How to: Use a Dictionary to Store Event Instances



One use for accessor-declarations is to expose many events without allocating a field for each event, but instead using a Dictionary to store the event instances. This is only useful if you have many events, but you expect most of the events will not be implemented.

Example

public delegate void EventHandler1(int i); public delegate void EventHandler2(string s);   public class PropertyEventsSample { private System.Collections.Generic.Dictionary<string, System.Delegate> eventTable;   public PropertyEventsSample() { eventTable = new System.Collections.Generic.Dictionary<string, System.Delegate>(); eventTable.Add("Event1", null); eventTable.Add("Event2", null); }   public event EventHandler1 Event1 { add { lock (eventTable) { eventTable["Event1"] = (EventHandler1)eventTable["Event1"] + value; } } remove { lock (eventTable) { eventTable["Event1"] = (EventHandler1)eventTable["Event1"] - value; } } }   public event EventHandler2 Event2 { add { lock (eventTable) { eventTable["Event2"] = (EventHandler2)eventTable["Event2"] + value; } } remove { lock (eventTable) { eventTable["Event2"] = (EventHandler2)eventTable["Event2"] - value; } } }

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

Одно из применений 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(); } }
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

· Use generic types to maximize code reuse, type safety, and performance.

· The most common use of generics is to create collection classes.

· The.NET Framework class library contains several new generic collection classes in the System.Collections.Generic namespace. These should be used whenever possible instead of classes such as ArrayList in the System.Collections namespace.

· You can create your own generic interfaces, classes, methods, events and delegates.

· Generic classes may be constrained to enable access to methods on particular data types.

· Information on the types that are used in a generic data type may be obtained at run-time by using reflection.


Универсальные шаблоны

Универсальные шаблоны были добавлены в язык C# версии 2.0 и среду CLR. Универсальные шаблоны в платформе.NET Framework представляют концепцию параметров типов, которые позволяют разрабатывать классы и методы, не придерживающиеся спецификации одного или нескольких типов до тех пор, пока класс или метод не будет объявлен клиентским кодом и пока не будет создан его экземпляр. Например, используя параметр универсального типа T можно написать отдельный класс, который другой клиентский код сможет использовать без риска привидения во время выполнения или операций упаковки-преобразования, как показано в следующем примере:

ß-----



Поделиться:


Последнее изменение этой страницы: 2017-01-19; просмотров: 94; Нарушение авторского права страницы; Мы поможем в написании вашей работы!

infopedia.su Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав. Обратная связь - 18.224.33.107 (0.004 с.)