반응형




전편 : http://3dmpengines.tistory.com/2001?category=509928


다음 예제에서는 abstract 속성을 정의하는 방법을 보여 줍니다. 추상 속성 선언은 속성 접근자의 구현을 제공하지 않습니다. 클래스가 속성을 지원하도록 선언하지만 접근자 구현은 파생 클래스에서 처리되도록 합니다. 다음 예제에서는 기본 클래스에서 상속된 추상 속성을 구현하는 방법을 보여 줍니다.

이 파일에서는 double 형식의 Area 속성을 포함하는 Shape 클래스를 선언합니다.


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
// compile with: csc -target:library abstractshape.cs
public abstract class Shape
{
    private string name;
 
    public Shape(string s)
    {
        // calling the set accessor of the Id property.
        Id = s;
    }
 
    public string Id
    {
        get
        {
            return name;
        }
 
        set
        {
            name = value;
        }
    }
 
    // Area is a read-only property - only a get accessor is needed:
     public abstract double Area
    {
        get;
    }
 
    public override string ToString()
    {
        return Id + " Area = " + string.Format("{0:F2}", Area);
    }
}

cs


다음 코드에서는 Shape의 세 가지 서브클래스와 이러한 서브클래스에서 Area 속성을 재정의하여 
고유한 구현을 제공하는 방법을 보여 줍니다.



// compile with: csc -target:library -reference:abstractshape.dll shapes.cs public class Square : Shape { private int side; public Square(int side, string id) : base(id) { this.side = side; } public override double Area { get { // Given the side, return the area of a square: return side * side; } } } public class Circle : Shape { private int radius; public Circle(int radius, string id) : base(id) { this.radius = radius; } public override double Area { get { // Given the radius, return the area of a circle: return radius * radius * System.Math.PI; } } } public class Rectangle : Shape { private int width; private int height; public Rectangle(int width, int height, string id) : base(id) { this.width = width; this.height = height; } public override double Area { get { // Given the width and height, return the area of a rectangle: return width * height; } } }




다음 코드에서는 많은 Shape 파생 개체를 만들고 해당 영역을 출력하는 테스트 프로그램을 보여 줍니다.

// compile with: csc -reference:abstractshape.dll;shapes.dll shapetest.cs class TestClass { static void Main() { Shape[] shapes = { new Square(5, "Square #1"), new Circle(3, "Circle #1"), new Rectangle( 4, 5, "Rectangle #1") }; System.Console.WriteLine("Shapes Collection"); foreach (Shape s in shapes) { System.Console.WriteLine(s); } } }

/* Output: Shapes Collection Square #1 Area = 25.00 Circle #1 Area = 28.27 Rectangle #1 Area = 20.00 */



이 샘플은 개별적으로 컴파일된 파일 3개로 구성되었으며, 결과로 생성된 어셈블리는 다음 컴파일 시 참조됩니다.

  • abstractshape.cs: 추상 Area 속성이 포함된 Shape 클래스입니다.

  • shapes.cs: Shape 클래스의 서브클래스입니다.

  • shapetest.cs: 일부 Shape 파생 개체의 영역을 표시할 테스트 프로그램입니다.

예제를 컴파일하려면 다음 명령을 사용합니다.

csc abstractshape.cs shapes.cs shapetest.cs

그러면 shapetest.exe 실행 파일이 생성됩니다.


ref : https://docs.microsoft.com/ko-kr/dotnet/csharp/programming-guide/classes-and-structs/how-to-define-abstract-properties

반응형

+ Recent posts