调用这个方法的正确语法是什么?
我正在尝试使用Prism(DryIoc)进行依赖注入。
给出以下类:
internal class MainWindowViewModel : BindableBase
{
private readonly ITestingService _testingService;
public MainWindowViewModel(ITestingService testingService, string someValue)
{
_testingService = testingService;
}
}
我已经为 ITestingService 注册了一个实现,但我想在解析时传入 someValue。
据我所见,我需要调用的 Resolve 方法的签名是:
public static T Resolve<T>(this IContainerProvider provider, params (Type Type, object Instance)[] parameters)
但我还没想清楚如何通过 params 参数传入 MainWindowViewModel 所需的字符串。
var mainViewModel = Container.Resolve<MainWindowViewModel>(?????);
我尝试过使用数组、匿名类型(new {Type=typeof(String), Instance="abc"}),但似乎都不对。
解决方案
该参数是一个元组类型。我期望这段代码能够编译:
var mainViewModel = Container.Resolve<MainWindowViewModel>((typeof(string), "abc"));
或者把它写得非常直观:
(Type Type, Object Instance) tuple = (typeof(string), "abc");
var mainViewModel = Container.Resolve<MainWindowViewModel>(tuple);
甚至通过不依赖 params 来让它更加明确:
(Type Type, Object Instance) tuple = (typeof(string), "abc");
var mainViewModel = Container.Resolve<MainWindowViewModel>(new[] { tuple });
请注意,这也等价于不提供元组元素名称,例如
(Type, Object) tuple = (typeof(string), "abc");
var mainViewModel = Container.Resolve<MainWindowViewModel>(new[] { tuple });
甚至
var tuple = (typeof(string), "abc");
var mainViewModel = Container.Resolve<MainWindowViewModel>(new[] { tuple });
有关元组类型的更多信息,请参阅 https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/value-tuples。
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。