我试图在Delphi 2009中的以下示例代码中实现clear.
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;
...
Run Code Online (Sandbox Code Playgroud)
如果"T"没有约束,我可以理解complie时间错误.但由于"T"必须是一个接口,我本以为这种语法会起作用.
有没有把FField设置为NIL,所以可以释放界面?
我正在尝试编写如下所示的通用缓存属性访问器,但在尝试检查存储变量是否已包含值时遇到编译器错误:
function TMyClass.GetProp<T>(var ADataValue: T; const ARetriever: TFunc<T>): T;
begin
if ADataValue = Default(T) then // <-- compiler error on this line
ADataValue := ARetriever();
Result := ADataValue;
end;
Run Code Online (Sandbox Code Playgroud)
我得到的错误是"E2015运算符不适用于此操作数类型".
我是否必须约束T才能使这项工作?帮助文件说Default()除了泛型类型之外会接受任何东西.在我的情况,我用简单的类型,如内容大都String,Integer和TDateTime.
或者是否有其他库函数来执行此特定检查?
我正在使用Delphi 2009以防万一.
PS:以防万一我从代码中不清楚我正在尝试做什么:在我的情况下,由于各种原因确定实际属性值可能需要一段时间,有时甚至根本不需要它们.在正面但是值是常量所以我只想调用第一次访问属性时确定实际值的代码,然后将值存储在类字段中,下次访问该属性时返回缓存值直.这是我希望能够使用该代码的示例:
type
TMyClass = class
private
FSomeProp: String;
function GetSomeProp: String;
function GetProp<T>(var ADataValue: T; const ARetriever: TFunc<T>): T;
public
property SomeProp read GetSomeProp;
end;
function GetSomeProp: String;
begin
Result := GetProp<String>(FSomeProp,
function: String
begin
Result …Run Code Online (Sandbox Code Playgroud)