gpt4 book ai didi

delphi - Delphi 中如何将泛型类型转换为实际类型

转载 作者:行者123 更新时间:2023-12-03 15:21:57 25 4
gpt4 key购买 nike

考虑以下代码

procedure TMyClass.SetParam<T>(Name: string; Value: T);
begin
if (TypeInfo(T) = TypeInfo(string)) then
begin
FHashTable.AddString(Name, (Value as string));
end
else if (TypeInfo(T) = TypeInfo(Integer)) then
begin
FHashTable.AddInteger(Name, (Value as Integer));
end
......

我想要一个通用过程,它获取类型 T 的通用值,并根据 T 的实际类型将该值插入到哈希表中。

编译器不会让我做这个转换,也不会让我做像 Integer(Value) 这样的事情。

有人可以解释一下我应该如何实现上述内容吗?

最佳答案

尝试这样的事情:

procedure TMyClass.SetParam<T>(Name: string; Value: T);
begin
if (TypeInfo(T) = TypeInfo(string)) then
begin
FHashTable.AddString(Name, PString(@Value)^);
end
else if (TypeInfo(T) = TypeInfo(Integer)) then
begin
FHashTable.AddInteger(Name, PInteger(@Value)^);
end
......

或者这个:

uses
System.Rtti;

procedure TMyClass.SetParam<T>(Name: string; Value: T);
var
LValue: TValue;
begin
LValue := TValue.From<T>(Value);
if (TypeInfo(T) = TypeInfo(string)) then
begin
FHashTable.AddString(Name, LValue.AsString);
end
else if (TypeInfo(T) = TypeInfo(Integer)) then
begin
FHashTable.AddInteger(Name, LValue.AsInteger);
end
......

关于delphi - Delphi 中如何将泛型类型转换为实际类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41459307/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com