[Delphi] Generic(제네릭) 예제

Clover·2022년 3월 29일
0

Delphi

목록 보기
8/12
post-thumbnail

"Delphi 2009" 버전부터 Generic(제네릭)을 지원하기 시작했다.

제네릭의 이점

  • 컴파일 단계에서 타입 체크를 한다. 따라서 incompatible type error를 방지할 수 있다.
  • 타입을 미리 지정하기 때문에, 하위 코드에서 형변환 횟수를 줄일 수 있다.
  • 코드의 재사용성을 높일 수 있다.

자바의 그것과 유사하게 디자인되어 있으므로, 자바를 먼저 공부했다면 쉽게 사용할 수 있을 것이다.


제네릭 클래스 선언 방법

TSample<T> = class  // T : Type. Object type도 인자로 받을 수 있다.
    private
      FValue :T;
    public
      function GetValue :T;
      procedure SetValue(param :T);
      property Value :T  read GetValue write SetValue;
  end;

간단 사용 방법

procedure GenericDemo;
var
  GenTestInt :TSample<Integer>;
  GenTestStr :TSample<string>;
begin
  //Integer Type
  GenTestInt := TSample<Integer>.Create;
  GenTestInt.Value := 1;
  ShowMessage(IntToStr(GenTestInt.GetValue));
 
  //String Type
  GenTestStr := TSample<string>.Create;
  GenTestStr.Value := '1';
  ShowMessage(GenTestStr.GetValue);
end;
  • 선언과 동시에 타입을 지정했기 때문에, GenTestInt.Value := 1 라인과 GenTestStr.Value 라인에서 형변환을 하지 않고도 대입할 수 있다.

0개의 댓글