0

这是我的类型...

unit unitTestInterfaces;

interface
type
  IFoo = interface
    ['{169AF568-4568-429A-A8F6-C69F4BBCC6F0}']
    function TestFoo1:string;
    function TestFoo:string;
  end;

  IBah = interface
    ['{C03E4E20-2D13-45E5-BBC6-9FDE12116F95}']
    function TestBah:string;
    function TestBah1:string;
  end;

  TFooBah = class(TInterfacedObject, IFoo, IBah)
    //IFoo
    function TestFoo1:string;
    function TestFoo:string;

    //IBah
    function TestBah1:string;
    function TestBah:string;
  end;

implementation

{ TFooBah }

function TFooBah.TestBah: string;
begin
  Result := 'TestBah';
end;

function TFooBah.TestBah1: string;
begin
  Result := 'TestBah1';
end;

function TFooBah.TestFoo: string;
begin
  Result := 'TestFoo';
end;

function TFooBah.TestFoo1: string;
begin
  Result := 'TestFoo1';
end;

end.

这是我运行示例的代码...

var
  fb:TFooBah;
  f:IFoo;
  b:IBah;
begin
  try
    fb := TFooBah.Create;

    /// Notice we've used IBah here instead of IFoo, our writeln() still outputs the
    /// result from the TestBah() function, presumably because it's the "first" method
    /// in the IBah interface, just as TestFoo1() is the "first" method in the IFoo
    /// interface.
    (fb as IUnknown).QueryInterface(IBah,f); //So why bother with this way at all??
    //f := fb as IBah; //causes compile error
    //f := fb; //works as expected
    if Assigned(f)then
    begin
      writeln(f.TestFoo1); //wouldn't expect this to work since "f" holds reference to IBah, which doesn't have TestFoo1()
    end;

    (fb as IUnknown).QueryInterface(IBah,b);
    if Assigned(f) then
    begin
      writeln(b.TestBah1);
    end;

  except on E:Exception do
    writeln(E.Message);
  end;
end.

似乎在第一次调用 QueryInterface 时,即使我们为“f”变量分配了错误类型的接口,它仍然会尝试执行它所指向的任何东西的“第一个”方法,而不是与名称“TestFoo1”。使用 f := fb 可以按预期工作,那么我们是否有理由使用 QueryInterface 而不是语法 f := fb?

4

3 回答 3

7

我猜你在这里违反了规则:

QueryInterface 会将您请求的接口放入 f 中。您有责任确保 f 属于适当的类型。由于第二个参数没有类型,编译器无法警告您您的错误。

于 2010-08-11T12:53:03.383 回答
3

我认为更好的语法既不是QueryInterface一也不是f := fb一。这是您注释掉的那个:

f := fb as IBah; //causes compile error

那正是因为它具有类型检查功能,这涵盖了QueryInterface它不检查其参数的问题。

于 2010-08-11T13:09:34.013 回答
2

请注意 f := Fb 作为 IFoo,调用 Supports(Fb, IFoo) 等 tec 都在后台调用 QueryInterface。因此使用了 QueryInterface 方法,但是您可以通过自动转换获得很好的语法,is,as 和支持之类的方法。

于 2010-08-11T13:07:51.727 回答