delphi – 这是返回空泛型值的正确方法吗?
发布时间:2020-12-15 09:10:06 所属栏目:大数据 来源:网络整理
导读:我有一个HashTable,我需要一些方法来返回一个not_found结果. type TCellT = record ..... property key: cardinal read FKey write FKey; property data: T read FData write FData; end; THashTableT = class(TEnumerableT) private FCells: array of TCell
我有一个HashTable,我需要一些方法来返回一个not_found结果.
type TCell<T> = record ..... property key: cardinal read FKey write FKey; property data: T read FData write FData; end; THashTable<T> = class(TEnumerable<T>) private FCells: array of TCell<T>; FEmpty: T; ... constructor Create(InitialSize: cardinal); overload; function Lookup(key: cardinal): T; ... end; constructor THashTable<T>.Create(InitialSize: cardinal); begin inherited Create; // Initialize regular cells FArraySize:= InitialSize; Assert((FArraySize and (FArraySize - 1)) = 0); // Must be a power of 2 SetLength(FCells,FArraySize); FillChar(FEmpty,SizeOf(FEmpty),#0); //Superfluous I know,just there to //demonstrate the point. end; 鉴于上述结构,如何返回未找到的结果? 所以我想出了下面的解决方案: function THashTable<T>.Lookup(key: cardinal): T; var Cell: NativeUInt; begin if (key <> 0) then begin // Check regular cells Cell:= First_Cell(IntegerHash(key)); while (true) do begin if (FCells[Cell].key = key) then Exit(FCells[Cell].data); if not (FCells[Cell].key = 0) then Exit(FEmpty); <<-- is this correct? Cell:= Circular_Next(Cell); end; end else begin Result:= FEmpty; <<--- Can I return an empty generic like this? end; end; 我可以返回零初始化的泛型来表示没有结果吗? 或者我会遇到结构化类型(类/记录/变体/字符串等)的问题. 请注意,当T是整数时,我确实理解了歧义.零可能是一个有效的值,因此它与not_found无法区分. 解决方法
您正在寻找的是默认值(T),它将为任何类型T返回零值.
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |