3.泛型介面-C#高階程式設計
阿新 • • 發佈:2019-01-26
using System;
namespace Wrox.ProCSharp.Generics
{
public class Shape
{
public double Width { get; set; }
public double Height { get; set; }
public override string ToString()
{
return String.Format("Width: {0}, Height: {1}", Width, Height);
}
}
}
namespace Wrox.ProCSharp.Generics
{
public class Rectangle : Shape
{
}
}
namespace Wrox.ProCSharp.Generics
{
// contra-variant
//泛型介面的抗變-介面只能把泛型型別T用作其方法的輸入
public interface IDisplay<in T>
{
void Show(T item);
}
}
namespace Wrox.ProCSharp.Generics
{
// covariant
//泛型介面的協變-返回型別只能是T
public interface IIndex<out T>
{
T this [int index] { get; }
int Count { get; }
}
}
using System;
namespace Wrox.ProCSharp.Generics
{
public class RectangleCollection : IIndex<Rectangle>
{
private Rectangle[] data = new Rectangle[3]
{
new Rectangle { Height=2, Width=5 },
new Rectangle { Height=3, Width=7 },
new Rectangle { Height=4.5, Width=2.9}
};
private static RectangleCollection coll;
public static RectangleCollection GetRectangles()
{
return 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
{
get
{
return data.Length;
}
}
}
}
using System;
namespace Wrox.ProCSharp.Generics
{
public class ShapeDisplay : IDisplay<Shape>
{
public void Show(Shape s)
{
Console.WriteLine("{0} Width: {1}, Height: {2}", s.GetType().Name, s.Width, s.Height);
}
}
}
using System;
namespace Wrox.ProCSharp.Generics
{
class Program
{
static void Main()
{
IIndex<Rectangle> rectangles = RectangleCollection.GetRectangles();
IIndex<Shape> shapes = rectangles;
for (int i = 0; i < shapes.Count; i++)
{
Console.WriteLine(shapes[i]);
}
IDisplay<Shape> shapeDisplay = new ShapeDisplay();
IDisplay<Rectangle> rectangleDisplay = shapeDisplay;
rectangleDisplay.Show(rectangles[0]);
}
}
}