0

我正在尝试将我的应用从 Delphi XE8 转换为 10.2 Tokyo。我遇到了奇怪的运行时异常,它使用了由接口 acrocss 包( bpl's )提供的强制转换对象。当我尝试使用“as”关键字强制转换对象时,我在运行时遇到了这个异常:

Project Project1.exe 引发异常类 EInvalidCast,并带有消息“无效的类类型转换”

这是代码:

单独包中的接口 Plugin_interface.bpl :

unit MainIntf;

interface
  Type IMainInft = interface
  ['{FE08C4A2-069C-4B8C-BB1B-445348CAB6A0}']
    function GetForm : TObject;
  end;

implementation

end.

Project1.exe 中提供的接口实现:

unit MainImpl;

interface
uses MainIntf;

  Type TMain = class(TInterfacedObject,IInterface,IMainInft)
    function GetForm : TObject;
end;


implementation
uses unit1;

function TMain.GetForm: TObject ;
begin
  result:=Form1; // interafce is implemented on the main form so Form1 is rechable form here
end;


end.

最后在另一个包“plugin.bpl”中,我试图从接口获取对象:

unit Plugin_main;

interface
uses Mainintf, Vcl.Forms;

type TPlugin = class (Tobject)
  IIMyRefernceToMianIntf: IMainInft;
end;

function RegisterPlugin(AMainIntf: IMainInft): TForm ; export;
procedure UnRegisterPlugin; export;

exports
  RegisterPlugin,
  UnRegisterPlugin;

var
 Plugin_obj:  TPlugin;

implementation
uses vcl.Dialogs,System.Classes ;

function RegisterPlugin(AMainIntf: IMainInft): TForm ;
var
 MyForm : TForm ;
begin
  Plugin_obj:=TPlugin.Create;
  Plugin_obj.IIMyRefernceToMianIntf:=AMainIntf;

  if AMainIntf.GetForm is TForm then
    Showmessage ('Great it is a Tform') // will not happen
  else
    Showmessage ('Sorry  it is not Tform'); // will happen 
  if TComponent (AMainIntf.GetForm).Classname='TForm1' then
    Showmessage ('What ?? It is TForm1 decsendant from TForm  so is it TForm after all ?!');  // will happen 
// result:=  AMainIntf.GetForm as TForm  -- This will rise na exception
  result:= TForm( AMainIntf.GetForm)  ; // this will work

end;

procedure UnRegisterPlugin;
begin
  Plugin_obj.Free;
end;
end.

为什么我不能使用“as”和“is”关键字。只有硬猫会做,但我讨厌这样做。在 XE8 编译器上,一切都按预期工作 - XE 10.2 tokyo 编译器上存在问题

4

1 回答 1

-1

“is”关键字检查实际对象以查看它是否属于您所要求的类型。所以,检查这个:

if AMainIntf.GetForm is TForm then
Showmessage ('Great it is a Tform') // will not happen

不会发生,因为GetForm返回TObject而不是TForm。使用“is”检查也意味着您正在检查可铸造性,即使用“as”关键字的能力。由于“is”检查失败,因此该命令也会失败:

result:=  AMainIntf.GetForm as TForm;

您的下一个选择是按照您的方式对 GetForm 进行硬转换:

TForm(AMainIntf.GetForm);

之所以有效,是因为此转换不检查是否GetFormTForm类型。由于您在 中返回了一个表格TMain,因此这种硬铸造对您来说是安全的选择。

话虽如此,但是,您为什么不TForm直接返回而不是返回TObject呢?您是否IMainInft在返回其他类型以外的其他类中使用TForm

于 2017-06-22T13:17:36.187 回答