如何在Delphi

时间:2017-01-04 08:30:22

标签: delphi generics typeinfo

考虑以下代码

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)这样的事情。

有人可以解释我应该如何实施上述内容?

2 个答案:

答案 0 :(得分:4)

尝试这样的事情:

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
......

答案 1 :(得分:4)

虽然你可以轻松地使用类来完成这类事情,但对于其他类型,例如整数,字符串和枚举,它并不容易。尽管它们在一定程度上与泛型一起使用,但它们并不是很好。另一方面,在这种情况下,你不需要。

因为泛型是所以有用,所以当他们不是真的需要时,有很大的诱惑冲入泛型(我知道我已经不止一次陷入了这个陷阱)。这里所需要的只是重载函数,如下所示。

BytesIO

我创建了一个虚拟类THashTable仅用于说明目的,我还没有创建FHashTable。这只是为了说明原则。我知道代码不会按原样运行,但它会编译。

相关问题