如果我理解正确,这很好:
type
IMyInterface = interface['{60E314E4-9FA9-4E29-A09A-01B91F2F27C7}']
procedure MyMethod;
end;
type
TMyIClass = class(TInterfacedObject, IMyInterface)
public
procedure MyMethod; // Forget the implementations in this example
end;
var
lMyIClass: IMyInterface;
lSupports: Boolean;
begin
lMyIClass := TMyIClass.Create;
lSupports := Supports(lMyIClass,IMyInterface);
Memo1.Lines.Add('lMyIClass supports IMyInterface: ' + BoolToStr(lSupports,true));
if lSupports then DoSomethingWith(lMyIClass);
现在我有一个实现多个接口的类:
type
IFirstInterface = interface['{4646BD44-FDBC-4E26-A497-D9E48F7EFCF9}']
procedure SomeMethod1;
end;
ISecondInterface = interface['{B4473616-CF1F-4E88-9EAE-1AAF1B01A331}']
procedure SomeMethod2;
end;
TMyClass = class(TInterfacedObject, IFirstInterface, ISecondInterface)
procedure SomeMethod1;
procedure SomeMethod2;
end;
我可以调用另一个重载的 Support() 返回接口并用它做一些事情):
var
MyClass1,MyClass2 : TMyClass;
i1: IFirstInterface;
i2: ISecondInterface;
bSupports: Boolean;
begin
Memo1.Clear;
MyClass1 := TMyClass.Create;
bSupports := Supports(MyClass1,IFirstInterface,i1);
if bSupports then
begin
Memo1.Lines.Add('MyClass1 supports IFirstInterface');
DoSomethingWith(i1);
end
else
Memo1.Lines.Add('MyClass1 does not support IFirstInterface');
bSupports := Supports(MyClass1,ISecondInterface,i2);
if bSupports then
begin
Memo1.Lines.Add('MyClass1 supports ISecondInterface');
DoSomethingElseWith(i2);
end
else
Memo1.Lines.Add('MyClass1 does not support ISecondInterface');
MyClass1 := nil;
i1 := nil;
i2 := nil;
MyClass2 := TMyClass.Create;
bSupports := Supports(MyClass2,IFirstInterface,i1);
if bSupports then
begin
Memo1.Lines.Add('MyClass2 supports IFirstInterface');
DoSomethingWith(i1);
end
else
Memo1.Lines.Add('MyClass2 does not support IFirstInterface');
bSupports := Supports(MyClass2,ISecondInterface,i2);
if bSupports then
begin
Memo1.Lines.Add('MyClass2 supports ISecondInterface');
DoSomethingElseWith(i2);
end
else
Memo1.Lines.Add('MyClass2 does not support ISecondInterface');
我对此有三个问题:
现在
MyClass1, MyClass2
是对象类型,而不是简单示例中的接口类型。这个可以吗?我应该 Free() 还是“nil” MyClass1 或者甚至不理会它?
在处理了 2. 之后,
ix:= nil
关于引用计数是否仍然需要这两个语句?