# C# 协变与逆变

C# 专栏收录该内容
2 篇文章 0 订阅

“协变”->”和谐的变”->”很自然的变化”->string->object :协变。

“逆变”->”逆常的变”->”不正常的变化”->object->string 逆变。

## 协变

/// <summary>
/// 逆变
/// </summary>
/// <typeparam name="T"></typeparam>
public interface IDisplay<in T>
{
void Show(T item);
}
/// <summary>
/// 协变
/// </summary>
/// <typeparam name="T"></typeparam>
public interface IIndex<out T>
{
T this[int index] { get; }
int Count { get; }
}

 public class Shape
{
public double Whidth { get; set; }
public double Height { get; set; }

public override string ToString()
{
return $"Whidti:{Whidth},Height:{Height}"; } } public class Rectangle : Shape { }  协变 IIndex接口用RectangleCollection 类来实现  public class RectangleCollection : IIndex<Rectangle> { private Rectangle[] data = new Rectangle[3] { new Rectangle{Height=2,Whidth=5}, new Rectangle{ Height=3,Whidth=7}, new Rectangle{ Height=4.5,Whidth=2.9} }; private static RectangleCollection _coll; public static RectangleCollection GetRectangles() => _coll ?? (_coll = new RectangleCollection()); public Rectangle this[int index] { get { if (index < 0 || index > data.Length) throw new ArgumentOutOfRangeException("index"); return data[index]; } } public int Count => data.Length; }  控制台使用 //协变 IIndex<Rectangle> rectangles = RectangleCollection.GetRectangles(); IIndex<Shape> shape = rectangles; for (int i = 0; i < shape.Count; i++) { Console.WriteLine(shape[i]); }  ## 逆变  public class ShapeDisplay : IDisplay<Shape> { public void Show(Shape item) { Console.WriteLine($"{item.GetType().Name} Width:{item.Whidth},Height:{item.Height}");
}
}


  //逆变
IDisplay<Shape> shapeDisplay = new ShapeDisplay();
IDisplay<Rectangle> rectangleDisplay = shapeDisplay;
rectangleDisplay.Show(rectangles[0]);


• 0
点赞
• 0
评论
• 0
收藏
• 一键三连
• 扫一扫，分享海报

07-04 806

04-28 1357
06-11 1423
12-20 36
03-10 2063
12-15 44
01-20 674
10-27 79
09-25 331
09-05 69
08-19
08-04 8582
10-17 7725