我做了“可能重复”问题接受的答案所做的事情:
让对象实现IObject
接口:
IObject = interface(IUnknown)
['{39B4F98D-5CAC-42C5-AF8D-0237C8EFBE4C}']
function GetSelf: TObject;
end;
所以它会是:
var
thingy: IThingy;
o: TOriginalThingy;
begin
o := (thingy as IObject).GetSelf as TOriginalThingy;
更新:为了将要点带回家,您可以向现有对象添加新界面。
现有对象:
type
TOriginalThingy = class(TInterfacedObject, IThingy)
public
//IThingy
procedure DrinkCokeZero; safecall;
procedure ExcreteCokeZero; cafecall;
end;
添加IObject
为它公开的接口之一:
type
TOriginalThingy = class(TInterfacedObject, IThingy, IObject)
public
//IThingy
procedure DrinkCokeZero; safecall;
procedure ExcreteCokeZero; cafecall;
//IObject - provides a sneaky way to get the object implementing the interface
function GetSelf: TObject;
end;
function TOriginalThingy.GetSelf: TObject;
begin
Result := Self;
end;
典型用法:
procedure DiddleMyThingy(Thingy: IThingy);
var
o: TThingy;
begin
o := (Thingy as IObject).GetSelf as TThingy;
o.Diddle;
end;