When the method signature matches the delegate type, the covariant and inverter provide you with a certain degree of flexibility. The covariant allows a method to have more derived return types than those defined in the delegate. The inverse method allows fewer derived parameter types than the delegate type.
I. covariant
This example shows how to use a delegate with a method with a return type, which is derived from the return type in the delegate signature. BySecondHandlerThe returned data type isDogsType, which is defined by the delegateMammalsType.
class Mammals
{
}
class Dogs : Mammals
{
}
class Program
{
// Define the delegate.
public delegate Mammals HandlerMethod();
public static Mammals FirstHandler()
{
return null;
}
public static Dogs SecondHandler()
{
return null;
}
static void Main()
{
HandlerMethod handler1 = FirstHandler;
// Covariance allows this delegate.
HandlerMethod handler2 = SecondHandler;
}
}
Ii. Inverter
This example shows how to use a delegate with a method with a certain type of parameters, which are the base type of the delegate signature parameter type. Through the inverter, a number of different processing procedures must be used before, and now only one event processing program can be used for failover. For example, you can now create an event handler to receive parameters input by EventArgs, And then you can send the handler and a Button of the MouseEventArgs type (as a parameter. the MouseClick event can be used together with the TextBox that sends the KeyEventArgs parameter. the KeyDown event is used together.
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;
}
Source: MSDN