tl;博士:
嘗試將物件串列傳遞給函式,該函式需要實作介面的物件串列。所述物件實作該介面。編譯器不會允許它。
尋找替代解決方法或我的錯誤。
設定
我沒有使用實際的代碼,IMO 這應該無關緊要。對我來說似乎是一個概念問題。
該類TObjectWithInterface實作了介面ISomeInterface并擴展了該類TCustomInterfacedObject,它只是圍繞檔案中IInterface給出的參考計數作業。
TObjectWithInterface = class(TCustomInterfacedObject, ISomeInterface)
如果有一個程序,它采用實作該介面的物件串列:
procedure SomeFunction(List: TList<ISomeInterface>)
問題
在 的函式內部TObjectWithInterface,我嘗試使用 的物件串列呼叫該函式TObjectWithInterface:
procedure TObjectWithInterface.DoTheStuff(ListOfObjects: TList<TObjectWithInterface>)
begin
// ...
SomeFunction(ListOfObjects); // <-- Compiler error: Incompatible types
// ...
end;
編譯器告訴我以下內容:
E2010:不兼容的型別:“System.Generics.Collections.TList”和“System.Generics.Collections.TList”
愚蠢的解決方法
我真的不喜歡我目前的解決方法,它包括創建一個新串列并將每個型別轉換TObjectWithInterface為ISomeInterface:
procedure TObjectWithInterface.DoTheStuff(ListOfObjects: TList<TObjectWithInterface>)
var
ListOfInterfaceObjects: TList<ISomeInterface>;
begin
// ...
ListOfInterfaceObjects := TList<ISomeInterface>.Create;
for var Object in ListOfObjects do
ListOfInterfaceObjects.Add(Objects as ISomeInterface);
SomeFunction(ListOfInterfaceObjects)
// ...
end;
這對我來說似乎很hacky。我可能做了一些愚蠢的事情,或者沒有正確理解某些事情,因為這是我第一次嘗試在 Delphi 中使用介面。請不要生氣。
無論哪種方式,我都希望有人能指出我的錯誤,或者,如果這是語言限制,還有其他解決方法。
uj5u.com熱心網友回復:
您將物件串列復制到單獨的介面串列中的“解決方法”實際上是正確且適當的解決方案。您不能使用 a TList<X>where aTList<Y>是預期的,它們是不同且不相關的型別。僅僅因為您在介面上禁用參考計數并不會改變物件與其介面相關的記憶體布局,因此您仍然必須傳遞正確的記憶體指標,這意味著執行從一個到另一個的必要轉換。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/378975.html
