问题
I am trying to implement clear in the following example code in Delphi 2009.
interface
...
TFoo<T : IInterface> = class(TObject)
FField : T;
procedure Clear;
end;
...
implementation
...
procedure TFoo<T>.Clear;
begin
// Line Below Results In
// E2010 Incompatible types: 'T' and 'Pointer'
FField := nil;
end;
...
I could understand the complie time error if "T" was not constrained. But since "T" must be an Interface, I would have thought this syntax would have worked.
Is there away to set FField to NIL, so the interface can be released?
回答1:
Instead of nil
you must use the new Default(T)
which returns the default value for the generic parameter type. And for interfaces it is nil
procedure TFoo<T>.Clear;
begin
FField := Default(T);
end;
来源:https://stackoverflow.com/questions/907406/interfaces-with-generics-setting-to-nil