前天想写个泛型类,用来保存类类型(如TClass、TComponentClass之类)
但是DelphiXE的泛型约束不支持TClass
TClassList<T: TClass> 将会得到编译错误
因此我只能去掉约束条件 TClassList<T>
但是这样又有个问题,即 T 类型不明确,无法用 Assigned(T) 或 T <> nil 来判断值是否为空
后来想了个办法绕过了这个问题,详见代码
procedure TClassList<T>.Register(const ADisplayName: string; AClass: T);
var
P: Pointer;
begin
P := PPointer(@AClass)^;
Assert(Assigned(P), 'Target class cannot be nil.');
FClassList.AddObject(ADisplayName, P);
end;
function TClassList<T>.Find(const ADisplayName: string; out Value: T): Boolean;
var
Index: Integer;
begin
Assert(ADisplayName <> '', 'Display name cannot be blank.');
Index := FClassList.IndexOf(ADisplayName);
Result := Index >= 0;
if Result then PPointer(@Value)^ := Pointer(FClassList.Objects[Index]);
end;
var
P: Pointer;
begin
P := PPointer(@AClass)^;
Assert(Assigned(P), 'Target class cannot be nil.');
FClassList.AddObject(ADisplayName, P);
end;
function TClassList<T>.Find(const ADisplayName: string; out Value: T): Boolean;
var
Index: Integer;
begin
Assert(ADisplayName <> '', 'Display name cannot be blank.');
Index := FClassList.IndexOf(ADisplayName);
Result := Index >= 0;
if Result then PPointer(@Value)^ := Pointer(FClassList.Objects[Index]);
end;
记录一下,免得忘记