■ switch문에서 타입 패턴을 사용하는 방법을 보여준다.
▶ 예제 코드 (C#)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 |
using System; using System.Collections.Generic; #region 도형 출력하기 - PrintShape(shapeList) /// <summary> /// 도형 출력하기 /// </summary> /// <param name="shapeList">도형 리스트</param> private void PrintShape(List<Shape> shapeList) { foreach(Shape shape in shapeList) { switch(shape) { case null : Console.WriteLine("NULL"); break; case Circle circle : Console.WriteLine($"RADIUS={circle.Radius}"); break; case Rectangle rectangle when rectangle.Width == rectangle.Height : Console.WriteLine($"SIZE={rectangle.Width}"); break; case Rectangle rectangle : Console.WriteLine($"WIDTH={rectangle.Width},HEIGHT={rectangle.Height}"); break; default : Console.WriteLine(shape.ToString()); break; } } } #endregion /// <summary> /// 도형 /// </summary> public class Shape { } /// <summary> /// 원 /// </summary> public class Circle : Shape { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 반경 - Radius /// <summary> /// 반경 /// </summary> public double Radius { get; set; } #endregion } /// <summary> /// 사각형 /// </summary> public class Rectangle : Shape { //////////////////////////////////////////////////////////////////////////////////////////////////// Property ////////////////////////////////////////////////////////////////////////////////////////// Public #region 너비 - Width /// <summary> /// 너비 /// </summary> public double Width { get; set; } #endregion #region 높이 - Height /// <summary> /// 높이 /// </summary> public double Height { get; set; } #endregion } |