2017-04-19 1 views
0

Können Sie praktische Verwendung von Generika-Contravarianz geben (wird gut, wenn sowohl aus der Infrastruktur und benutzerdefinierte Beispiel).Gibt es eine praktische Verwendung von Contravariance in C#

Danke.

+3

Mögliches Duplikat [Kovarianz und die reale Welt Beispiel Kontra] (http://stackoverflow.com/fragen/2662369/kovarianz-und-contravarianz-real-world-beispiel) –

Antwort

0

Microsofts Dokumentation Verwendung ein sehr guter Ort, um diese Art von Beispielen zu finden:

https://msdn.microsoft.com/en-us/library/dd799517(v=vs.110).aspx

using System; 
using System.Collections.Generic; 

abstract class Shape 
{ 
    public virtual double Area { get { return 0; }} 
} 

class Circle : Shape 
{ 
    private double r; 
    public Circle(double radius) { r = radius; } 
    public double Radius { get { return r; }} 
    public override double Area { get { return Math.PI * r * r; }} 
} 

class ShapeAreaComparer : System.Collections.Generic.IComparer<Shape> 
{ 
    int IComparer<Shape>.Compare(Shape a, Shape b) 
    { 
     if (a == null) return b == null ? 0 : -1; 
     return b == null ? 1 : a.Area.CompareTo(b.Area); 
    } 
} 

class Program 
{ 
    static void Main() 
    { 
     // You can pass ShapeAreaComparer, which implements IComparer<Shape>, 
     // even though the constructor for SortedSet<Circle> expects 
     // IComparer<Circle>, because type parameter T of IComparer<T> is 
     // contravariant. 
     SortedSet<Circle> circlesByArea = 
      new SortedSet<Circle>(new ShapeAreaComparer()) 
       { new Circle(7.2), new Circle(100), null, new Circle(.01) }; 

     foreach (Circle c in circlesByArea) 
     { 
      Console.WriteLine(c == null ? "null" : "Circle with area " + c.Area); 
     } 
    } 
} 

/* This code example produces the following output: 

null 
Circle with area 0.000314159265358979 
Circle with area 162.860163162095 
Circle with area 31415.9265358979 
*/ 
Verwandte Themen