How do I test a generic type variable for equality with Default(T) in Delphi?

我怕爱的太早我们不能终老 提交于 2019-11-30 20:53:46

After a hint in the comments from Binis and digging around a little in Generics.Collections I came up with the following which appears to work just as I wanted it:

function TMyClass.GetProp<T>(var ADataValue: T; const ARetriever: TFunc<T>): T;
var
  lComparer: IEqualityComparer<T>;
begin
  lComparer := TEqualityComparer<T>.Default;
  if lComparer.Equals(ADataValue, Default(T)) then
    ADataValue := ARetriever();
  Result := ADataValue;
end;

As I understand things it looks like u want to do some kind of memoize functionality. If this is the case just read this article

http://blogs.teamb.com/craigstuntz/2008/10/01/37839/

The problem is not the Default function, but the equality operator =.

You could constrain T to IEquatable and use the Equals method like this:

TMyClass = class
  function GetProp<T : IEquatable<T>>(var ADataValue: T; const ARetriever: 
end;
...
function TMyClass.GetProp<T>(var ADataValue: T; const ARetriever: TFunc<T>): T;
begin  
if ADataValue.Equals (Default(T)) then
  ADataValue := ARetriever();  
Result := ADataValue;
end;   
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!