Howdey,德尔福 - 无法投TVirtualInterface到虚拟接口
我使用TVirtualInterface实现一些接口的基本接口。这些interfaes代表可以在数据库中找到的Keys。我使用定制的代码生成器生成接口定义。例如:
// Base code
IKey = interface
function KeyFields : string;
function KeyValues : Variant;
function GetKeyValue(const aKeyName : string) : Variant;
procedure SetKeyValue(const aKeyName : string; Value : Variant);
end;
// Generated code
ITable1Key = interface(IKey)
end;
ITable1Key1 = interface(ITable1Key)
procedure SetField1(const Value : string);
function GetField1 : string;
property Field1 : string read GetField1 write SetField1;
end;
ITable1Key2 = interface(ITable1Key)
procedure SetField1(const Value : string);
function GetField1 : string;
property Field1 : string read GetField1 write SetField1;
procedure SetField2(const Value : string);
function GetField2 : string;
property Field2 : string read GetField1 write SetField1;
end;
// Other generated declarations
我使用TVirtualInterface来实现每个IKey接口,而不是逐个实现它们。
虽然,在我TVirtualInterface:
TKey = TVirtualInterface
public
constructor Create(aType : PTypeInfo);
function Cast : IKey;
end;
TKey<T : IKey>
public
constructor Create; reintroduce;
function Cast : T;
end;
constructor TKey.Create(aType : PTypeInfo)
begin
inherited Create(aType, aHandlerMethod);
end;
function TKey.Cast;
var
pInfo: PTypeInfo;
begin
pInfo := TypeInfo(IKey);
if QueryInterface(GetTypeData(pInfo).Guid, Result) <> 0 then
begin
raise Exception.CreateFmt('Sorry, TKey is unable to cast %s to its interface ', [string(pInfo.Name)]);
end;
end;
constructor TKey<T>.Create;
begin
inherited Create(TypeInfo(T));
end;
function TKey<T>.Cast;
var
pInfo: PTypeInfo;
begin
pInfo := TypeInfo(T);
if QueryInterface(GetTypeData(pInfo).Guid, Result) <> 0 then
begin
raise Exception.CreateFmt('Sorry, TKey<T> is unable to cast %s to its interface ', [string(pInfo.Name)]);
end;
end;
我没有问题,铸造TKEY的虚拟接口使用TKey.Cast方法的T型,虽然TKey.Cast返回不支持错误接口。
我System.Rtti检查,这不是工作,我想它的方式部分:
function TVirtualInterface.QueryInterface(const IID: TGUID; out Obj): HResult;
begin
if iid = FIID then
begin
_AddRef;
Pointer(Obj) := @VTable;
Result := S_OK;
end
else
Result := inherited
end;
现在,我怎么能强迫TVirtualInterface将自己转换为IID作为父FIID字段的界面?我是否必须为IKey界面创建另一个TVirtualInterface实例?
非常感谢。
这是“限制”一个新问题吗?在Delphi中,你总是必须声明继承接口的实现,其中一个类直接实现派生接口和任何基接口,但接口实现是(或曾经是)从该基类自身声明的基类继承接口的实现。唯一的问题是如果基类实现了接口的方法而没有实际声明接口本身的实现。除非我的记忆力正在玩技巧(我目前没有德尔福交手测试)。 – Deltics
@Deltics:“*这个”限制“是一个新问题吗?*” - 不,它一直在那里。接口方法的实现可以像预期的那样通过普通多态性从基类继承到派生类,但是必须在每个派生类声明中指定接口以便出现在每个类的内部接口表中,所以'TObject.GetInterface() (通过扩展,'IInterface.QueryInterface()',''as''和'as'运算符,'SysUtils。Supports()'等)可以看到它。不理想,C++没有这个限制。 –