簡體   English   中英

Delphi Rtti獲取屬性-為什么這會導致AV?

[英]Delphi Rtti Get Property - Why does this results in AV?

我正在嘗試編寫一個規范實用程序庫。

規范之一是TExpressionSpecification。 基本上,它通過評估內部TExpression來實現Specification模式。

TExpression之一是TPropertyExpression。 它只是一個表達式,使用Rtti通過其名稱獲取屬性的值。

我以最簡單的方式實現了它,但實際上無法理解為什么它會向我拋出AV。

我全力以赴調試器。 所有類型都是它們應有的。 我只是不知道為什么TRttiProperty.GetValue會破壞嚴重。

有人可以幫忙嗎? 單位規格;

interface

uses

Classes;

type

TPropertyExpression<TObjectType, TResultType> = class

private
  FPropertyName: string;
public
  constructor Create(aPropertyName: string); reintroduce;
  function Evaluate(aObject: TObjectType): TResultType;
  property PropertyName: string read FPropertyName write FPropertyName;
end;

procedure TestIt;

implementation

uses

Rtti;

constructor TPropertyExpression<TObjectType, TResultType>.Create(aPropertyName:
    string);
begin
  inherited Create;
  PropertyName := aPropertyName;
end;

function TPropertyExpression<TObjectType, TResultType>.Evaluate(aObject:
    TObjectType): TResultType;
var
  aCtx : TRttiContext;
  aModelType : TRttiType;
  aResultType : TRttiType;
  aProperty : TRttiProperty;
  aValue : TValue;
begin
  aCtx := TRttiContext.Create;
  aModelType := aCtx.GetType(System.TypeInfo(TObjectType));
  aResultType := aCtx.GetType(System.TypeInfo(TResultType));
  aProperty := aModelType.GetProperty(PropertyName);
  aValue := aProperty.GetValue(Addr(aObject));
  Result := aValue.AsType<TResultType>;  
end;

procedure TestIt;
var
  aComponent : TComponent;
  aSpec : TPropertyExpression<TComponent, string>;
begin
  aComponent := TComponent.Create(nil);
  aComponent.Name := 'ABC';
  aSpec := TPropertyExpression<TComponent, string>.Create('Name');
  WriteLn(aSpec.Evaluate(aComponent));
  Readln; 
end;

end.

GetValue需要實例指針( aObject ),但是您正在aObject傳遞指針變量( @aObject )的地址。

將您的TObjectType約束為一個類類型:

type
  TPropertyExpression<TObjectType: class; TResultType> = class...

然后,代替Addr(aObject) ,直接傳遞實例:

  aValue := aProperty.GetValue(Pointer(aObject));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM