例如,我想決議一個傳入 TComponent 和 TNotifyEvent 的類,如下所示,但呼叫的是 TObject 的基本建構式而不是 TMy。
GlobalContainer.RegisterType<TMy>;
GlobalContainer.RegisterFactory<Func<TComponent,TNotifyEvent,TMy>>(TParamResolution.ByType);
var F:=GlobalContainer.Resolve<Func<TComponent,TNotifyEvent,TMy>>;
F(Self,Self.OnActivate);
我可以通過撰寫一些如下所示的非常丑陋的代碼來解決這個問題,但我認為這種解決方案非常普遍,以至于我一定做錯了什么。
TOther = class
end;
TMy = class
public
constructor Create(C: TComponent; N: TNotifyEvent; O: TOther);
end;
procedure TForm2.Button1Click(Sender: TObject);
begin
GlobalContainer.RegisterType<TOther>;
GlobalContainer.RegisterType<TMy>;
GlobalContainer.RegisterType<Func<TComponent,TNotifyEvent,TMy>>(
function: Func<TComponent,TNotifyEvent,TMy>
begin
Result:=Func<TComponent,TNotifyEvent,TMy>(
function(O: TComponent; N: TNotifyEVent): TMy
begin
Result:=TMy.Create(O,N,GlobalContainer.Resolve<TOther>);
end
);
end
);
GlobalContainer.Build;
var F:=GlobalContainer.Resolve<Func<TComponent,TNotifyEvent,TMy>>;
F(Self,Self.OnActivate);
end;
constructor TMy.Create(C: TComponent; N: TNotifyEvent; O: TOther);
begin
OutputDebugString('Resolved');
end;
在此先感謝您的任何指點。
uj5u.com熱心網友回復:
在開發中的最新提交之后,這現在應該可以作業了。
問題是型別化引數決議系結到引數型別而不是引數型別。在這種情況下,這導致型別化的值TForm2(取自傳遞的引數)與型別建構式的 C 引數的型別不匹配,TComponent因為匹配檢查型別標識而不是賦值兼容性。
修復后,型別化引數決議完全適用于工廠函式的引數型別,而不是可能(在物件的情況下)更窄的實際引數型別。
FWIW 以供將來參考 - 當手動注冊工廠時,通常不需要使用RegisterType提供委托,但可以在沒有任何捕獲狀態時直接使用RegisterInstance(請記住const` 引數):Spring.Func<...> has
GlobalContainer.RegisterInstance<Func<TComponent,TNotifyEvent,TMy>>(
function(const O: TComponent; const N: TNotifyEVent): TMy
begin
// ....
end);
編輯:我還添加了自動檢測以獲得最佳引數解析度默認值。當工廠型別為 aSpring.Func<...>時,它會自動使用ByType,因此可以從RegisterFactory呼叫中省略。對于所有其他型別,它ByName像以前一樣默認使用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/471633.html
上一篇:如何插入或連接兩個程式?
