2013-10-03 2 views
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; 

을 내가 아닌 객체의 유형을 비교하려면 어떻게합니까?

여기 여기,

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. 

답변

5

그냥 System.Rtti.TValue 사용 :

관련 부분은 여기 DSharp을 언급 대한

function TDefiniteValue<T>.ToString: string; 
var 
    v: TValue; 
begin 
    v := TValue.From<T>(FTheValue); 
    Result:= ' definitly ' + v.ToString; 
end; 
3

DSharp이 유닛 단지 그 목적이있는 SSCCE의 링크입니다 :

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

IT는 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; 
.... 
+0

일을하지만 필요하지 않습니다 :) –

관련 문제