3

显然,以下代码将不起作用:

....
property value: T read FTheValue;
....
function TDefiniteValue<T>.toString: string;
begin
  Result:= ' definitly ';
  if (value is TObject) then Result:= Result + TObject(value).ToString
  else if (value is integer) then Result:= Result + IntToStr(integer(value));
  //                ^^^^^^^
  //                +++++++-- integer is not an object
end;

如何比较非对象的类型?

这是一个SSCCE

Program Maybe; 

interface

uses
  System.Generics.Collections, System.SysUtils;

type    
  TDefiniteValue<T> = class(TEnumerable<T>)
  strict private
    FTheValue: T;
  strict protected
    function toString: string; override;
    property value: T read FTheValue;
  end;

implementation

function TDefiniteValue<T>.toString: string;
begin
  Result:= ' definitly ';
  if (value is TObject) then Result:= Result + TObject(value).ToString
  else if (value is integer) then Result:= Result + IntToStr(integer(value));
  //                ^^^^^^^
  //                +++++++-- integer is not an object.
end;

begin
end.
4

2 回答 2

5

Just use System.Rtti.TValue:

function TDefiniteValue<T>.ToString: string;
var
  v: TValue;
begin
  v := TValue.From<T>(FTheValue);
  Result:= ' definitly ' + v.ToString;
end;
于 2013-10-04T06:02:01.097 回答
3

DSharp 有一个专门用于此目的的单元,链接如下:

https://code.google.com/p/delphisorcery/source/browse/trunk/Source/Core/DSharp.Core.Reflection.pas

它包含一个类助手列表Rtti。这使您可以询问您的对象。

相关部分在这里:

TValue = Rtti.TValue;

{$REGION 'Documentation'}
/// <summary>
/// Extends <see cref="Rtti.TValue">TValue</see> for easier RTTI use.
/// </summary>
{$ENDREGION}
TValueHelper = record helper for TValue
private
function GetRttiType: TRttiType;
class function FromFloat(ATypeInfo: PTypeInfo; AValue: Extended): TValue; static;
public
function IsFloat: Boolean;
function IsNumeric: Boolean;
function IsPointer: Boolean;
function IsString: Boolean;

function IsInstance: Boolean;
function IsInterface: Boolean;

// conversion for almost all standard types
function TryConvert(ATypeInfo: PTypeInfo; out AResult: TValue): Boolean; overload;
function TryConvert<T>(out AResult: TValue): Boolean; overload;

function AsByte: Byte;
function AsCardinal: Cardinal;
....
于 2013-10-03T16:52:15.943 回答