加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-15 09:35:20 所属栏目:大数据 来源:网络整理
导读:请考虑以下代码 procedure TMyClass.SetParamT(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.AddI
请考虑以下代码

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

有人可以解释我应该如何实现上述?

解决方法

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

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

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.这只是为了说明原则.我知道代码不会按原样运行,但它会编译.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读