TypeCasting : what is difference between below 2 lines of code?

社会主义新天地 提交于 2019-12-23 17:27:08

问题


what is the difference between below 2 lines of code. Both are trying to get the path and one is working and other is throwing error. i am working on Delphi-7

Path:= (((FFormOwner as TForm).Designer) as IDesigner).GetPrivateDirectory; --Working
Path:= IDesigner(TForm(FFormOwner).Designer).GetPrivateDirectory ;  --Error

Below is the code which is using line of code to get the path.

constructor TsampleComponent.Create(AOwner: TComponent);
begin
  inherited Create(AOwner);
  FFormOwner:=TForm(Owner);
  if not (Owner is TForm) then
    repeat
      FFormOwner:=TForm(FFormOwner.Owner);
    until (FFormOwner is TForm) or (FFormOwner.Owner=nil);

  if (csDesigning in ComponentState) then
    Path:= (((FFormOwner as TForm).Designer) as IDesigner).GetPrivateDirectory
  else
    Path:=ExtractFilePath(Application.EXEName);
.
.

end;

回答1:


IDesigner(TForm(FFormOwner).Designer)

This performs a simple reinterpretation cast of Designer. It will fail because Designer is of type IDesignerHook which is not the same as IDesigner.

(FFormOwner as TForm).Designer) as IDesigner

This performs a runtime query for IDesigner and is resolved with a call to QueryInterface. This is the correct way to obtain a different interface from an existing one.



来源:https://stackoverflow.com/questions/30637832/typecasting-what-is-difference-between-below-2-lines-of-code

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!