mgh*_*hie 2 delphi generics delphi-2009
我正在查看Delphi 2009试用版,但是立即遇到了仿制药问题.
下面的代码没有编译,我没有丝毫想到为什么它给了我E2015的Equals()方法:
type
TPrimaryKey<T> = class(TObject)
strict private
fValue: T;
public
constructor Create(AValue: T);
function Equals(Obj: TObject): boolean; override;
function GetValue: T;
end;
constructor TPrimaryKey<T>.Create(AValue: T);
begin
inherited Create;
fValue := AValue;
end;
function TPrimaryKey<T>.Equals(Obj: TObject): boolean;
begin
Result := (Obj <> nil) and (Obj is TPrimaryKey<T>)
and (TPrimaryKey<T>(Obj).GetValue = fValue);
end;
function TPrimaryKey<T>.GetValue: T;
begin
Result := fValue;
end;
Run Code Online (Sandbox Code Playgroud)
为什么编译器认为无法比较fValue和GetValue()的结果?
如果T是一个字符串怎么办?如果它是TSize记录怎么办?
在不约束T的情况下(例如,使用<T:class>),您无法确定比较是否有意义.
相反,如果要比较T类型的两个值,可以使用Generics.Defaults单元并使用:
TEqualityComparer<T>.Default.Equals(x, y)
Run Code Online (Sandbox Code Playgroud)
比较类型T的值x和y
归档时间: |
|
查看次数: |
1292 次 |
最近记录: |