所以,我再次学习新事物,遇到了智能指针。我有代码
procedure TForm3.BitBtn1Click(Sender: TObject);
var
_StringList: ISmartPointer<TStringList>;
begin
_StringList := TSmartPointer<TStringList>.Create(TStringList.Create);
end;
您看到的变量声明有点奇怪,需要简化。我遇到了另一个解决方案
procedure TForm3.btnDelphiClick(Sender: TObject);
var
_StringList: TStringList;
begin
_StringList := SmartGuard.SmartGuard<TStringList>(TStringList.Create(False));
end;
可悲的是,它不适用于无参数构造函数
procedure TForm3.btnDelphiClick(Sender: TObject);
var
_StringList: TStringList;
begin
_StringList := SmartGuard.SmartGuard<TStringList>(TStringList.Create);
end;
[DCC32错误] main.pas(47(:e2089无效Typecast
我在这里不幸吗?P.S.我知道你们中有些人会争辩说我应该坚持尝试。
unit SmartGuard;
interface
type
IGuard = interface
['{CE522D5D-41DE-4C6F-BC84-912C2AEF66B3}']
end;
TGuard = class(TInterfacedObject, IGuard)
private
FObject: TObject;
public
constructor Create(AObject: TObject);
destructor Destroy; override;
end;
SmartGuard<T: class> = record
private
FGuard: IGuard;
FGuardedObject: T;
public
class operator Implicit(GuardedObject: T): SmartGuard<T>;
class operator Implicit(Guard: SmartGuard<T>): T;
end;
implementation
uses
{Delphi}
System.SysUtils
{Project}
;
constructor TGuard.Create(AObject: TObject);
begin
FObject := AObject;
end;
destructor TGuard.Destroy;
begin
FObject.Free;
inherited;
end;
{ SmartGuard }
class operator SmartGuard<T>.Implicit(GuardedObject: T): SmartGuard<T>;
begin
Result.FGuard := TGuard.Create(GuardedObject);
Result.FGuardedObject := GuardedObject;
end;
class operator SmartGuard<T>.Implicit(Guard: SmartGuard<T>): T;
begin
Result := Guard.FGuardedObject;
end;
end.
我很想找到一个不需要其他"方法"的解决方案,如此处https://github.com/marcocantu/delphisessions/blob/master/master/delphilanguagecoderage2018/02_smartpointers/smartpointers/smartpointerters/smartpointerclass.pas.pas.pas e.g._StringList.Value.Add('foo');
和"特殊"支架,例如_StringList := TSmartPointer<TStringList>.Create(TStringList.Create)();
编译器需求帮助歧义
TStringList.Create
编译器不知道这是对方法的引用还是对该方法的调用。
通过添加parens来表示歧义,以指示这是一个呼叫。
_StringList := SmartGuard.SmartGuard<TStringList>(TStringList.Create());