delphi - 如何在 Delphi 中从泛型转换为变体

标签 delphi generics delphi-xe rtti variant

我有一个 Delphi 泛型类,它公开一个带有泛型类型参数的函数。在这个函数中,我需要将泛型类型的实例传递给另一个需要 Variant 类型的对象。与此类似:

type
  IMyInterface = interface
    DoStuff(Value: Variant);
  end;      

  TMyClass<T> = class
    FMyIntf: IMyInterface
    procedure DoStuff(SomeValue: T);
  end;

[...]

procedure MyClass<T>.DoStuff(SomeValue: T);
begin
  FMyIntf.DoStuff((*convert SomeValue to Variant here*));
end;

我尝试使用 Rtti.TValue.From(SomeValue).AsVariant。这对于整数类型有效,但对于 bool 类型则不然。我不太明白为什么,因为通常我可以为 Variant 分配一个 bool 值...

有没有更好的方法来进行这种转换?我只需要它来处理简单的内置类型(不包括枚举和记录)

最佳答案

我认为没有直接的方法将泛型类型转换为变体,因为变体无法容纳所有可能的类型。您必须编写特定的转换例程。例如:

interface
//...
type
  TDemo = class
  public
    class function GetAsVariant<T>(const AValue: T): Variant;
  end;
//...
implementation
uses
  Rtti,
  TypInfo;
//...

{ TDemo}

class function TDemo.GetAsVariant<T>(const AValue: T): Variant;
var
  val: TValue;
  bRes: Boolean;
begin
  val := TValue.From<T>(AValue);
  case val.Kind of
    tkInteger: Result := val.AsInteger;
    tkInt64: Result := val.AsInt64;
    tkEnumeration: 
    begin
      if val.TryAsType<Boolean>(bRes) then
        Result := bRes
      else
        Result := val.AsOrdinal;
    end;
    tkFloat: Result := val.AsExtended;
    tkString, tkChar, tkWChar, tkLString, tkWString, tkUString:
      Result := val.AsString;
    tkVariant: Result := val.AsVariant
    else
    begin
      raise Exception.Create('Unsupported type');
    end;
  end;
end;

由于TValue.AsVariant在内部处理大部分类型转换,因此可以简化此函数。我将处理枚举,以防您稍后需要它们:

class function TDemo.GetAsVariant<T>(const AValue: T): Variant;
var
  val: TValue;
begin
  val := TValue.From<T>(AValue);
  case val.Kind of
    tkEnumeration:
    begin
      if val.TypeInfo = TypeInfo(Boolean) then
        Result := val.AsBoolean
      else
        Result := val.AsOrdinal;
    end
    else
    begin
      Result := val.AsVariant;
    end;
  end;

可能的用途:

var
  vValue: Variant;
begin
  vValue := TDemo.GetAsVariant<Boolean>(True);
  Assert(vValue = True); //now vValue is a correct Boolean

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

相关文章:

android - FMX TEdit 在启用自动更正时复制第一个输入

database - 如何在应用程序中恢复/重试损坏的 TADOConnection?

Delphi XE4 - 在 DLL 中动态创建表单导致 AV

c# - 具有泛型参数的 Asp.net 方法

Java 8 需要强制转换,而 Java 7 不需要 - enum.getClass/getDeclaringClass

delphi - 函数指针 - 初始值

delphi - 如何将上下文菜单附加到 TChromium 浏览器

delphi - 将 ImgView32 透明图层保存为 PNG

c# - 我需要一些 C# 泛型说明

delphi - 无法将 Indy 更新到最新版本