728x90
    
    
  반응형
    
    
    
  C#도 C++처럼 abstract를 사용함으로써 가상 클래스를 만들 수 있다. 대신 C++에서 사용하던 virtual를 사용하지 않아도 된다는 점은 다르다. abstract/override 키워드를 사용하면 된다. C++의 final은 존재하지 않은 듯하고 sealed와 readonly, const를 사용하여 해결하는 것 같다. (이건 다음 공부 할 때)
public abstract class Shape
{
    private string name;
    public Shape(string s)
    {
        Id = s;
    }
    public string Id
    {
        get
        {
            return name;
        }
        set
        {
            name = value;
        }
    }
    public abstract double Area
    {
        get;
    }
    public override string ToString()
    {
        return Id + " Area = " + string.Format("{0:F2}", Area);
    }
}
해당 Shape 클래스는 상속을 통해서 사용될 수 있고, Area 함수는 override 키워드를 통해서 정의 가능하다.
public class Square : Shape
{
    private int side;
    public Square(int side, string id) : base(id)
    {
        this.side = side;
    }
    public override double Area
    {
        get
        {
            return side * side;
        }
    }
}
이런 방법으로 정사각형, 원, 직사각형을 만들 수 있다.
namespace AbstractClassTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Shape[] shapes = { new Square(5, "Square #1"), new Circle(3, "Circle #1"), new Rectangle(4, 5, "Rectangle #1") };
            Console.WriteLine("Shapes Collection");
            foreach (Shape s in shapes)
            {
                Console.WriteLine(s);
            }
            Console.ReadKey();
        }
    }
}
결과
728x90
    
    
  반응형
    
    
    
  'Program Language > C#' 카테고리의 다른 글
| [C#] Generic Array (0) | 2023.02.16 | 
|---|---|
| [C#] 구조체와 클래스 (0) | 2023.02.16 | 
| [C#] OCX에 포인터 데이터 넘기기 (0) | 2022.10.26 | 
| [C#] C++로 만들어진 OCX 사용하기 (0) | 2022.10.26 | 
| [C#] C#에서 OCX를 사용할 때 LicenseException 에러 발생 (0) | 2022.10.26 | 
