Delphi   发布时间:2022-04-11  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了delphi – 将泛型与不同约束相结合大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_675_0@
我有这个原子乐观的初始化类:
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)^,nil) = nil then
      tmpIntf.Free;
  end;
  Result := storage;
end;

我可以在两个单独的类中完成这两个,但我真的想把两个初始化器放在同一个伞下.我想,我最好还是喜欢这个

var
  o: TObject;
  i: IInterface;

Atomic<TObject>.Initialize(o,CreateObject);
Atomic<IInterface>.Initialize(i,CreateInterfacE);

找不到任何好的解决方案.我得到的唯一想法是将类声明为Atomic< T> (没有约束)然后以某种方式(还不知道如何)在运行时检查T的RTTI并相应地继续.

我不太喜欢这个想法,我正在寻找一个更好的方法.

解决方法

您似乎无法指定“类或接口”类型的约束.因此,最简单的解决方案似乎是删除约束(您可以在运行时使用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 – 将泛型与不同约束相结合全部内容,希望文章能够帮你解决delphi – 将泛型与不同约束相结合所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。