Delphi interface inheritance: Why can't I access ancestor interface's members?

前端 未结 4 1181
温柔的废话
温柔的废话 2020-12-06 17:43

Assume you have the following:

//Note the original example I posted didn\'t reproduce the problem so
//I created an clean example  
  type
    IParent = inte         


        
4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-06 18:05

    The problem is not in the interface declarations or class implementations, but in your consumer code:

    procedure CallDoSomething(Parent: TParent);
    begin
      if Parent is TChild then
        TChild(Parent).DoSomething;  // << This is wrong
    end;
    

    Is not going to work because TChild does not have a method "DoSomething". If TChild implemented IChild directly, then this would normally be possible because TChild would implement the method directly AND as part of the IChild interface.

    Note however, that if TChild implemented DoSomething in PRIVATE scope, it would remain accessible thru the interface but normal scoping rules would mean that you still couldn't invoke it (from outside the class/uni) using a TChild reference either.

    In your case, you simply need to obtain the appropriate interface and then invoke the method you require thru the interface:

      if Parent is TChild then
        (Parent as IChild).DoSomething;
    

    However, you are using a class type test to determine (infer) the presence of an interface, relying on an implementation detail (knowledge that TChild implements IChild). I suggest you should instead be using interface testing directly, to isolate this dependency from those implementation details:

      var
        parentAsChild: IChild;
    
      begin
        if Parent.GetInterface(IChild, parentAsChild) then
          parentAsChild.DoSomething;
      end;
    

提交回复
热议问题