[英]How to declare variable type as generic?
I am creating a double linked list class and I am trying to change the type of data that the list is storing when the object is created.我正在创建一个双链表类,并且我正在尝试更改创建对象时列表存储的数据类型。
TItem = record
value: string;
address, prev, next: integer;
end;
TDoubleLinkedList = class
private
length, head, tail: integer;
data: array of TItem;
public
constructor Create;
procedure add(value: string);
function get(address: integer): string;
property Values[address: integer]: string read get; default;
end;
Is there any way to declare TItem.value as having a variable type than can be changed when the object is created?有没有办法将 TItem.value 声明为具有在创建对象时可以更改的变量类型? I want to be able to (in a separate unit) call something analogous to array of type and have TItem.value be that type.
我希望能够(在一个单独的单元中)调用类似于数组类型的东西,并将 TItem.value 设为该类型。
I want to be able to (in a separate unit) call something analogous to array of type and have TItem.value be that type.
我希望能够(在一个单独的单元中)调用类似于数组类型的东西,并将 TItem.value 设为该类型。
Depending on your real needs, you may choose from:根据您的实际需求,您可以选择:
Is there any way to declare TItem.value as having a variable type that can be changed when the object is created?
有没有办法将 TItem.value 声明为具有可以在创建对象时更改的变量类型?
Make your record and class using generics , so the type of data[x].value
is bound to the type T
of the TDoubleLinkedList
.使用泛型创建您的记录和类,因此
data[x].value
的类型绑定到TDoubleLinkedList
的类型T
type
TItem<T> = record
value: T;
address, prev, next: integer;
end;
TDoubleLinkedList<T> = class
private
length, head, tail: integer;
data: array of TItem<T>;
public
constructor Create;
procedure add(value: T);
function get(address: integer): T;
property Values[address: integer]: T read get; default;
end;
Example usage:用法示例:
var
dll_int: TDoubleLinkedList<integer>;
dll_string: TDoubleLinkedList<string>;
begin
dll_int := TDoubleLinkedList<integer>.Create;
try
dll_int.add(42);
writeln(dll_int.get(0)); // returns 42
finally
dll_int.Free;
end;
dll_string := TDoubleLinkedList<string>.Create;
try
dll_string.add('Test');
writeln(dll_string.get(0)); // returns 'Test'
finally
dll_string.Free;
end;
end.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.