logo
CSharp_Prog_Guide

Пример 1 (ковариация) Описание

В данном примере демонстрируется использование делегатов с методами, типы возвращаемых значений которых являются производными от типа возвращаемого значения в подписи делегата. Тип данных, возвращаемый SecondHandler, является типом Dogs, производным от заданного в делегате типа Mammals.

Код

------

Example 2 (Contravariance)

Description

This example demonstrates how delegates can be used with methods that have parameters of a type that are base types of the delegate signature parameter type. With contravariance, you can now use one event handler in places where, previously, you would have had to use separate handlers. For example, you can now create an event handler that accepts an EventArgs input parameter and use it with the Button.MouseClick event that sends a MouseEventArgs type as a parameter, and also with TextBox.KeyDown event that sends a KeyEventArgs parameter.

Code

System.DateTime lastActivity;

public Form1()

{

InitializeComponent();

lastActivity = new System.DateTime();

this.textBox1.KeyDown += this.MultiHandler; //works with KeyEventArgs

this.button1.MouseClick += this.MultiHandler; //works with MouseEventArgs

}

// Event hander for any event with an EventArgs or

// derived class in the second parameter

private void MultiHandler(object sender, System.EventArgs e)

{

lastActivity = System.DateTime.Now;

}