代码中为每个形状指定了序号,如果再来一颗子弹,让你要按类型打印的同时,还要按照序号从小到大排列怎么做呢?
1 using System; 2 using System.Collections.Generic; 3 4 namespace DesignPattern 5 { 6 class Program 7 { 8 public static readonly string[] OrderStrings = 9 { 10 nameof(Square), 11 nameof(Circle), 12 null 13 }; 14 15 static void Main(string[] args) 16 { 17 // 产生若干个随机图形 18 Random random = new Random(); 19 var shapes = new List<Shape>(); 20 for (int i = 0; i < 100; i++) 21 { 22 var value = random.Next(0, 10); 23 if (value < 5) 24 { 25 shapes.Add(new Square() { Index = i }); 26 } 27 else 28 { 29 shapes.Add(new Circle() { Index = i }); 30 } 31 } 32 33 // 画出所有随机图形 34 //shapes.ForEach(shape => shape.Draw()); 35 36 // 并发画出所有随机图形 37 //Parallel.ForEach(shapes, shape => { shape.Draw(); }); 38 39 // 按先圆形后正方形的顺序画出所有图形 40 shapes.Sort( 41 (shape, shape1) => 42 { 43 if (shape < shape1) 44 { 45 return -1; 46 } 47 48 if (shape > shape1) 49 { 50 return 1; 51 } 52 53 return 0; 54 }); 55 shapes.ForEach(shape => shape.Draw()); 56 57 Console.ReadLine(); 58 } 59 } 60 61 public class Shape 62 { 63 public int Index { get; set; } 64 65 public virtual void Draw() 66 { 67 Console.WriteLine($"画了Shape基类{Index}"); 68 } 69 70 public static bool operator <(Shape left, Shape right) 71 { 72 var leftTypeName = left.GetType().Name; 73 var leftIndex = -1; 74 var rightTypeName = right.GetType().Name; 75 var rightIndex = -1; 76 for (int i = 0; i < Program.OrderStrings.Length; i++) 77 { 78 if (leftTypeName == Program.OrderStrings[i]) 79 { 80 leftIndex = i; 81 } 82 83 if (rightTypeName == Program.OrderStrings[i]) 84 { 85 rightIndex = i; 86 } 87 } 88 return leftIndex < rightIndex; 89 } 90 91 public static bool operator >(Shape left, Shape right) 92 { 93 return !(left < right); 94 } 95 } 96 97 public class Square:Shape 98 { 99 public override void Draw() 100 { 101 Console.WriteLine($"画了正方形{Index}"); 102 } 103 } 104 105 public class Circle : Shape 106 { 107 public override void Draw() 108 { 109 Console.WriteLine($"画了圆{Index}"); 110 } 111 } 112 }查看代码