繁体   English   中英

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

[英]How to cast a generic type into an actual type in Delphi

请考虑以下代码

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

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

因为仿制药是非常有用的, 所以当它们不是真正需要时,有很大的诱惑要急于进入仿制药(我知道我已经不止一次陷入了这个陷阱)。 这里所需要的只是重载函数,如下所示。

unit UnitTest1;

interface

type
  THashTable = class
    procedure AddString( const pName : string; pValue : string ); virtual; abstract;  // dummy for illustration only
    procedure AddInt( const pName : string; const pInt : integer ); virtual; abstract;  // dummy for illustration only
  end;

  TMyClass = class
  private
    FHashTable : THashTable;
  public
    procedure TestString;
    procedure TestInt;

    procedure SetParam( const pName : string; const pValue : string ); overload;
    procedure SetParam( const pName : string; const pValue : integer ); overload;

  end;

implementation

{ TMyClass }

procedure TMyClass.SetParam(const pName, pValue: string);
begin
  FHashTable.AddString( pName, pValue );
end;

procedure TMyClass.SetParam(const pName: string; const pValue: integer);
begin
  FHashTable.AddInt( pName, pValue );
end;

procedure TMyClass.TestInt;
begin
  SetParam( 'Int', 4 );
end;

procedure TMyClass.TestString;
begin
  SetParam( 'Int', 'Fred' );
end;

end.

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM