13.3.3 在委託中使用可變性和複雜情況
阿新 • • 發佈:2018-12-11
1 public interface IShape 2 { 3 double Area { get; } 4 5 System.Windows.Rect BoundingBox { get; } 6 } 7 /// <summary> 8 /// WindowsBase.dll下 9 /// </summary> 10 public sealed class Circle : IShape 11 { 12 privateView Codereadonly System.Windows.Point center; 13 public System.Windows.Point Center { get { return center; } } 14 15 private readonly double radius; 16 public double Radius { get { return radius; } } 17 18 public Circle(System.Windows.Point center, int radius) 19 {20 this.center = center; 21 this.radius = radius; 22 } 23 24 public double Area 25 { 26 get { return Math.PI * radius * radius; } 27 } 28 29 public System.Windows.Rect BoundingBox 30 { 31 get 32{ 33 return new System.Windows.Rect(center - new System.Windows.Vector(radius, radius), new System.Windows.Size(radius * 2, radius * 2)); 34 } 35 } 36 } 37 public sealed class Square : IShape 38 { 39 private readonly Point topLeft; 40 private readonly double sideLength; 41 42 public Square(Point topLeft, double sideLength) 43 { 44 this.topLeft = topLeft; 45 this.sideLength = sideLength; 46 } 47 48 public double Area { get { return sideLength * sideLength; } } 49 50 public Rect BoundingBox 51 { 52 get { return new Rect(topLeft, new Size(sideLength, sideLength)); } 53 } 54 }
1 class Program 2 { 3 delegate T Func<out T>(); 4 delegate void Action<in T>(T obj); 5 static void Main(string[] args) 6 { 7 Func<Square> squareFactory = () => new Square(new Point(5, 5), 10); 8 Func<IShape> shapeFactory = squareFactory; 9 10 Action<IShape> shapePrinter = shape => Console.WriteLine(shape.Area); 11 Action<Square> squarePrinter = shapePrinter; 12 13 shapePrinter(shapeFactory()); 14 squarePrinter(squareFactory()); 15 } 16 }
13.3.4 複雜情況