이전 post을 기반으로 다음 코드를 작성했습니다. 이 게시물의 자세한 내용을 용서해주십시오. 모든 당사자가 전체 코드를 테스트하고 의견을 제시 할 수 있도록하는 것이 더 바람직하다고 생각합니다. 현실 세계에서 TInt
및 TStr
의 생성자뿐만 아니라 Low, High: integer
및 Length: integer
매개 변수를 활용하는 것이델파이 : generics and 'is'-operator problem
program sandbox;
{$APPTYPE CONSOLE}
uses
SysUtils,
Generics.Collections;
type
TDataType = class
// Stuff common to TInt and TStr
end;
TInt = class(TDataType)
FValue: integer;
constructor Create(Value, Low, High: integer);
end;
TStr = class(TDataType)
FValue: string;
constructor Create(Value: string; Length: integer);
end;
TSomeClass = class
FIntList: TList<TInt>;
FStrList: TList<TStr>;
procedure AddToList<T: TDataType>(Element: T);
constructor Create();
procedure Free();
end;
constructor TInt.Create(Value, Low, High: Integer);
begin
inherited Create();
FValue := Value;
end;
constructor TStr.Create(Value: string; Length: Integer);
begin
inherited Create();
FValue := Value;
end;
procedure TSomeClass.AddToList<T>(Element: T);
begin
if TObject(Element) is TInt then
FIntList.Add(Element)
else if TObject(Element) is TStr then
FStrList.Add(Element);
end;
constructor TSomeClass.Create();
begin
inherited;
FIntList := TList<TInt>.Create();
FStrList := TList<TStr>.Create();
end;
procedure TSomeClass.Free();
var
SomeIntItem: TInt;
SomeStrItem: TStr;
begin
for SomeIntItem in FIntList do begin
SomeIntItem.Free();
end;
for SomeStrItem in FStrList do begin
SomeStrItem.Free;
end;
FIntList.Free();
FStrList.Free();
end;
var
Inst: TSomeClass;
begin
try
{ TODO -oUser -cConsole Main : Insert code here }
Inst := TSomeClass.Create;
Inst.AddToList(TInt.Create(100, 0, 101));
Inst.AddToList(TStr.Create('Test', 10));
Inst.Free;
except
on E:Exception do
Writeln(E.Classname, ': ', E.Message);
end;
end.
참고. if TObject(Element) is TInt then
에 "E2089 Invalid typecast"가 있고, Delphi 2009를 실행하는 else if TObject(Element) is TStr then
에 있습니다. 왜 이런 일이 발생하는지 알고 계십니까?
편집 : TInt
및 TStr
은 아마도 10-20 개의 다른 유형 중 2 가지 일뿐입니다. 그렇지 않으면 작업에 대한 공구 인 이 과부하됩니다. :)
귀하의 선언과 AddToList의 구현은 다르다. 제네릭에 대해서는 충분히 알지 못하지만 정기적 인 파스칼에 대해서는 잘못되었습니다. –
안녕 Lieven! "프로 시저 AddToList (요소 : T)"와 달리 "프로 시저 TSomeClass.AddToList (요소 : T)"구현을 언급하고 있다고 생각하십니까? 그렇다면 귀하의 의견에 대한 응답은 RAD Studio가 실제 구현에 대한 제약을 원하지 않는다는 것입니다. –
conciliator
아, 알겠습니다. 아직 가장 명확한 것은 제네릭에 아직 들어 있지 않은 사람들을위한 것입니다. 그것을 지워 줘서 고마워. –