由于我昨天提出的问题可能并不完全清楚,而且我没有得到我想要的答案,我将尝试以更一般的方式制定它:
有没有办法基于实例化的泛型类型的实际类型实现特殊行为,使用明确的条件语句或使用某种特化?伪代码:
TGenericType <T> = class
function Func : Integer;
end;
...
function TGenericType <T>.Func : Integer;
begin
if (T = String) then Exit (0);
if (T is class) then Exit (1);
end;
...
function TGenericType <T : class>.Func : Integer;
begin
Result := 1;
end;
function TGenericType <String>.Func : Integer;
begin
Result := 0;
end;
Run Code Online (Sandbox Code Playgroud) 有没有办法确定作为方法参数传递的变量的类型?考虑班级:
TSomeClass = class
procedure AddToList<T: TDataType; U: TListClass<T>>(Element: T; List: U);
end;
Run Code Online (Sandbox Code Playgroud)
与方法实现
procedure TSomeClass.AddToList<T, U>(Element: T; List: U);
begin
if Element is TInt then
List.AddElement(TInt.Create(XXX))
else if Element is TString then
List.AddElement(TString.Create(YYY));
end;
Run Code Online (Sandbox Code Playgroud)
其中TInt.Create()和TString.Create()具有不同的参数集,但它们都继承自TDataType.
现在,我知道 - is操作员不能像这样使用,但是有没有合法的替代方案来做我在这里要求的事情?