In programming languages, "covariant" refers to the ability to use a more derived type than the original specified derived type. "contravariant" refers to the ability to use a less derived type. In. NET Framework 4 and Visual Studio 2010, both C # and visual Basic support the use of covariance and contravariance in generic interfaces and delegates, and allow the implicit conversion of generic type parameters.
If a generic interface or delegate's generic parameter is declared covariant or contravariant, the generic interface or delegate is called a Variant. Both C # and Visual Basic allow you to create your own variant interfaces and delegates. Non-generic delegates also support covariance and contravariance in terms of matching method signatures and delegate types. This allows you not only to assign a method with a matching signature to a delegate, but also to assign a method that returns a more derived type (covariant) than a derived type specified by a delegate type, or accepts a parameter (contravariance) of a type that is less derived by comparison.
Instance
First, define an interface Icolor and two derived classes
public interface IColor { }
public class Red : IColor { }
public class Blue : IColor { }
Defines the Colordemo class used to write display covariance and contravariance logic
public class ColorDemo{}
Write specific implementation
public class Colordemo
{
Covariant delegates
Private delegate T Covariancedelegate<out t> ();
Inverter delegate
Private delegate void Contravariancedelegate<in t> (T color);
private static string Colorinfo;
public void Coremethod ()
{
Co-change
covariancedelegate<icolor> A1 = Colormethod;
A1. Invoke ();
covariancedelegate<red> A2 = Redmethod;
A2. Invoke ();
a1 = A2;
A1. Invoke ();
Contravariance
contravariancedelegate<blue> B1 = Bluemethod;
B1. Invoke (New Blue ());
contravariancedelegate<icolor> b2 = Colormethod;
B2. Invoke (New Red ());
B1 = B2;
B1. Invoke (New Blue ());
}
private void Invoke (dynamic invokeobj)
{
Console.WriteLine ("Invokeobj type is:" + invokeobj.gettype (). Name);
Invokeobj.invoke ();
}
Private Icolor Colormethod ()
{
Colorinfo = "colorless";
Console.WriteLine (Colorinfo);
return null;
}
private void Colormethod (icolor color)
{
Colorinfo = "colorless";
Console.WriteLine (Colorinfo);
}
Private Red Redmethod ()
{
Colorinfo = "Red";
Console.WriteLine (Colorinfo);
return new Red ();
}
private void Bluemethod (blue blue)
{
Colorinfo = "Blue";
Console.WriteLine (Colorinfo);
}
}
Run results
static void Main(string[] args)
{
ColorDemo colorDemo =new ColorDemo();
colorDemo.CoreMethod();
Console.ReadLine();
}