与泛型的接口 - 设置为NIL [英] Interfaces with Generics - Setting to NIL

查看:121
本文介绍了与泛型的接口 - 设置为NIL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 界面
...我试图在下面的示例代码中明确实现它。
TFoo< T:IInterface> = class(TObject)
FField:T;
程序清除;
end;
...
执行
...
程序TFoo< T> .Clear;
begin
//在结果下面的行在
// E2010不兼容的类型:'T'和'指针'
FField:= nil;
end;
...

如果T不受约束,我可以理解complie time error 。
但是因为T必须是一个接口,所以我会认为这个语法会有
的工作。



是否需要将FField设置为NIL,所以界面可以被释放?

解决方案

而不是 nil 你必须使用新的 Default(T),它返回通用参数类型的默认值。对于接口,它是 nil

  procedure TFoo< T> .Clear ; 
begin
FField:=默认(T);
end;


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?

解决方案

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;

这篇关于与泛型的接口 - 设置为NIL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆