c# 协变与抗变
定義
補充:
代碼展示
public class 協變和抗變 {/// <summary>/// 基類/// </summary>public class Shape{public double Width { get; set; }public double Height { get; set; }public override string ToString() => $"width:{Width},height:{Height}";}/// <summary>/// 派生類/// </summary>public class Rect : Shape{}#region 協變接口/// <summary>/// 協變接口 --------------- 協變--》屬性和索引器必須實現get/// </summary>public interface IIndex<out T> // out聲明接口為協變類型接口,繼承了該接口的對象可以實現協變的隱式轉換。 --對應調用方法中的shapes{T this[int index] { get; }int Count { get; }}/// <summary>/// 接口實現類/// </summary>public class RectCollection : IIndex<Rect>{private Rect[] data = new Rect[3] {new Rect{ Height=2,Width=5},new Rect{ Height=3,Width=7},new Rect{ Height=4.5,Width=2.9},};private static RectCollection _coll;public static RectCollection GetRect() => _coll ?? (_coll = new RectCollection());public Rect this[int index]{get{if (index < 0 || index > data.Length)throw new ArgumentOutOfRangeException("index is out of range");return data[index];}}public int Count => data.Length;}#endregion#region 抗變接口/// <summary>/// 抗變接口 --------------- 抗變--》屬性和索引器必須實現set/// </summary>public interface IDisplay<in T> // in聲明接口為抗變類型接口,繼承了該接口的對象可以實現抗變的隱式轉換。 --對應調用方法中的rectDisplay{void Show (T item);}/// <summary>/// 抗變實現類/// </summary>public class ShapeDisplay : IDisplay<Shape>{public void Show(Shape item) => Console.WriteLine($"{item.GetType().Name} width:{item.Width} height:{item.Height}");}#endregionstatic void Main(){// 協變調用 Rect-》Shape 向派生程度低的類裝換IIndex<Rect> rects = RectCollection.GetRect();IIndex<Shape> shapes = rects; // 如果IIndex接口的參數沒有使用out修飾為協變,則轉換報錯(隱式轉換會編譯錯誤,顯示轉換會運行錯誤)for (int i = 0; i < shapes.Count; i++){Console.WriteLine(shapes[i]);}// 抗變調用 Shape-》Rect 向派生程度高的類轉換IDisplay<Shape> shapeDisplay = new ShapeDisplay();IDisplay<Rect> rectDisplay = shapeDisplay; // 如果IDisplay接口的參數沒有使用in修飾為抗變,則轉換報錯rectDisplay.Show(rects[0]);} }轉載于:https://www.cnblogs.com/LTEF/p/10127607.html
總結
- 上一篇: 插入排序(c++实现)
- 下一篇: X星球居民小区的楼房全是一样的...