作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有这个原子乐观初始化类:
type
Atomic<T: IInterface> = class
type TFactory = reference to function: T;
class function Initialize(var storage: T; factory: TFactory): T;
end;
class function Atomic<T>.Initialize(var storage: T; factory: TFactory): T;
var
tmpIntf: T;
begin
if not assigned(storage) then begin
tmpIntf := factory();
if InterlockedCompareExchangePointer(PPointer(@storage)^, PPointer(@tmpIntf)^, nil) = nil then
PPointer(@tmpIntf)^ := nil;
end;
Result := storage;
end;
现在我想为对象实现相同的模式。
type
Atomic<T: class> = class
type TFactory = reference to function: T;
class function Initialize(var storage: T; factory: TFactory): T;
end;
class function Atomic<T>.Initialize(var storage: T; factory: TFactory): T;
var
tmpIntf: T;
begin
if not assigned(storage) then begin
tmpIntf := factory();
if InterlockedCompareExchangePointer(PPointer(@storage)^, PPointer(@tmpIntf)^, nil) = nil then
tmpIntf.Free;
end;
Result := storage;
end;
我可以在两个单独的类中执行这两个操作,但我真的很想将两个初始值设定项放在同一个保护伞下。 IOW,我理想地想用它作为
var
o: TObject;
i: IInterface;
Atomic<TObject>.Initialize(o, CreateObject);
Atomic<IInterface>.Initialize(i, CreateInterface);
我找不到任何好的解决方案。我唯一的想法是将类声明为 Atomic<T>
(没有约束)然后以某种方式(还不知道如何)在运行时检查 T 的 RTTI 并相应地继续。
我不太喜欢这个想法,我正在寻找更好的方法。
最佳答案
您似乎无法指定“类或接口(interface)”类型的约束。因此,最简单的解决方案似乎是放弃约束(您可以使用 RTTI 在运行时强制执行它)。
对于 RTTI 方法,您可以使用 TypeInfo
功能:
uses
..., TypInfo;
class function Atomic<T>.Initialize(var storage: T; factory: TFactory): T;
var
tmpT: T;
begin
if not assigned(PPointer(@storage)^) then begin
tmpT := factory();
if InterlockedCompareExchangePointer(PPointer(@storage)^, PPointer(@tmpT)^, nil) = nil then begin
case PTypeInfo(TypeInfo(T))^.Kind of
tkInterface:
PPointer(@tmpT)^ := nil;
tkClass:
TObject(tmpT).Free;
else
raise Exception.Create('Atomic<T>.Initialize: Unsupported type');
end;
end;
end;
Result := storage;
end;
关于delphi - 将泛型与不同的约束相结合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8325895/
我是一名优秀的程序员,十分优秀!