Interfaces with Generics - Setting to NIL

浪子不回头ぞ 提交于 2020-02-03 03:15:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!