泛型 class 中的隐式类型参数

Implicit type argument in generic class

假设我有带强类型参数的 ViewModel 我使用 NavigationService 接受页面类型作为参数, 当不正确类型的参数传递给 Navigate 方法时。 然后我希望编译器抛出一个错误。

到目前为止我写了以下内容:

interface IPageViewModel<TParameter>    

void Navigate<TViewModel, TParameter>(TParameter argument) 
            where TViewModel : IPageViewModel<TParameter>;

class PageWithStringParameter : IPageViewModel<string>

为什么这不起作用?

navigationService.Navigate<PageWithStringParameter>("some string");

如果我将 PageWithStringParameter 作为 TViewModel 参数传递,TParameter 必须是字符串类型,因为它实现了 IPageViewModel。 传递 TParameter 类型参数是多余的。

有什么办法,如何避免这样写:

navigationService.Navigate<PageWithStringParameter, string>("some string");

编译器错误非常令人困惑,特别是如果我还有 NavigateMethod 的无参数重载

方法Navigate有两个通用的两类参数。您只提供一个。不能部分指定类型参数。您要么指定所有这些,要么指定其中的 none(在这种情况下都应隐式解析)

您可以考虑的一种接口方法是使用不带参数的 Navigate return 操作对象,如下所示:

public class Operations<TViewModel>
{
    void To<TParameter>(TParameter argument);
}

Operations<TViewModel> Navigate<TViewModel>();

因此您可以这样调用操作:

navigationService.Navigate<PageWithStringParameter>().To("some string");

不幸的是,您失去了使用 "where" 子句限制类型的能力,但您可以使用代码来做到这一点。