这两组代码有什么不同

Ste*_*eve 4 delphi oop interface

这两段代码之间有什么区别

type
  IInterface1 = interface
    procedure Proc1;
  end;

  IInterface2 = interface
    procedure Proc2;
  end;

  TMyClass = class(TInterfacedObject, IInterface1, IInterface2)
  protected
    procedure Proc1;
    procedure Proc2;
  end;
Run Code Online (Sandbox Code Playgroud)

以下内容:

type
  IInterface1 = interface
    procedure Proc1;
  end;

  IInterface2 = interface(Interface1)
    procedure Proc2;
  end;

  TMyClass = class(TInterfacedObject,  IInterface2)
  protected
    procedure Proc1;
    procedure Proc2;
  end;
Run Code Online (Sandbox Code Playgroud)

如果它们是同一个,那么它们是否有任何优点或可读性问题.

我想第二个意味着你不能编写一个实现IInterface2的类而不实现IInterface1,而第一个你可以.

Bar*_*lly 6

如果我们讨论的是Delphi for Win32(Delphi for .NET有不同的规则),那么两段代码的效果会有很大不同,并且几乎没有相同之处.

  1. 实现了接口的类必须实现该接口的祖先的所有成员,但它并没有暗示实施祖先.因此,尝试将类型为TMnClass的实例分配给类型为IInterface1的位置将对第二种情况失败.
  2. 与前一点相关,如果IInterface1和IInterface2都具有GUID,则在第二种情况下,对于TMyClass的实例,具有目标类型IInterface1的接口引用的动态转换(使用Supports或' as')将失败.
  3. 接口IInterface2在第二种情况下有一个额外的方法,它在第一种情况下没有.
  4. 第二种情况下类型IInterface2的值可分配给IInterface1类型的位置; 第一种情况并非如此.

在这个例子中看看你自己:

    type
      A_I1 = interface
      end;

      A_I2 = interface(A_I1)
      end;

      A_Class = class(TInterfacedObject, A_I2)
      end;

    procedure TestA;
    var
      a: A_Class;
      x: A_I1;
    begin
      a := A_Class.Create;
      x := a; // fails!
    end;

    type
      B_I1 = interface
      end;

      B_I2 = interface
      end;

      B_Class = class(TInterfacedObject, B_I1, B_I2)
      end;

    procedure TestB;
    var
      a: B_Class;
      x: B_I1;
    begin
      a := B_Class.Create;
      x := a; // succeeds!
    end;

    begin
      TestA;
      TestB;
    end.
Run Code Online (Sandbox Code Playgroud)