在 Delphi 中是否可以创建泛型类操作符或泛型指针?
AppleList[1].Color:=9999;
writeln(AppleList[1].Color); //Expected result is 9999
目标是这个或类似的,但有一个语法错误:
IList<T>=interface
function GetItem(const aIndex:integer):T;
function GetRef(const aIndex:integer):^T; //!!!!Syntax ERROR
property Items[const aIndex:integer]:T read GetItem;
property RefItems[const aIndex:integer]:^T read GetRef; //!!!!Syntax ERROR
end;
TList<T>=class(TInterfacedObject,IList<T>)
function GetItem(const aIndex:integer):T;
function GetRef(const aIndex:integer):^T;
...
property Items[const aIndex:integer]:T read GetItem;
property RefItems[const aIndex:integer]:^T read GetRef;default;
class operator Implicit(a:T):^T;
end;
TApple=record //or class
Size:double;
Color:integer;
end;
begin
var AppleList:IList<TApple>;
AppleList:=TList<TApple>.Create;
var apple:TApple;
apple.Color:=10;
AppleList.Add(apple);
AppleList.Items[1].Color:=9999;
writeln(AppleList[1].Color); //result is 10 instead of 9999 //NOT WORKS!!!!
AppleList.RefItems[1].Color:=2;
writeln(AppleList.RefItems[1].Color); //result:2 //It WORKS
AppleList[1].Color:=3;
writeln(AppleList[1].Color); //result:3 //It WORKS
//AppleList:=nil; no need! it is interface!
end.
1条答案
按热度按时间zsbz8rwp1#
记录是通过值传递的,而不是通过引用传递的。这就是为什么你会得到错误的输出。将TApple更改为Tobject的类。然后通过调用AppleList.Items[1],你会得到一个对苹果的引用,其中的Color值会被更改。