类型形参不能与类型实参一起使用



我想在单元测试项目中编写一个助手方法,它将初始化演示器,设置视图实例并设置演示器状态。

它抛出了一个例外:

类型形参不能与类型实参一起使用

代码:

public static **TPresenter<TView>** Initialize<TPresenter,TView>()
    where TPresenter: BasePresenter<TView>, new()
    where TView : new()
{
}

几分钟后,我发现问题是我的返回类型TPresenter<Tview>

我读了一些帖子,没有清楚地解释为什么我不能说T1<T2>

我被迫通过引用参数进行演示者分配。欢迎任何解释!

基本上没有办法说类型参数是本身具有特定数量类型参数的泛型类型-为了使TPresenter<TView>有意义,您需要能够做到这一点。

让它通过引用形参工作是什么意思并不清楚——不管你用什么类型的引用形参作为返回类型都是可以的。我猜它只是TPresenter类型,而不是TPresenter<TView>

没有TPresenter<TView>这种东西,这是没有意义的。TPresenter只是一个占位符,直到它被限制在它可以是任何东西的地方,例如没有int<tview>,所以你不能拥有它。一旦你添加了约束就意味着它必须是BasePresenter<TView>或者某种派生类型所以它总是Something<TView>所以TPresenter<TView>是没有意义的

这是一个旧的,但我击中了它。在Class定义中,只使用单个类型,然后在使用它的地方使用多个类型。例句:

public class Template1<T>{}
void SomeFunc()
{
    <Template1<SomeClass1,SomeClass2>> someValue = new <Template1<SomeClass1,SomeClass2>>()
}
//or even:
void SomeOtherFunc<U,V>()
{
    <Template1<U,V>> someValue = new <Template1<U,V>>();
}

我在我的代码中得到类似的错误。@Jon Skeet正确地指向了正确的方向。返回类型已经是泛型的,如TPresenter : BasePresenter<TView>所指定的。因此,我们可以简单地使用它作为TPresenter而不是TPresenter<TView>

public class BasePresenter<T>
{
}
public class Demo
{
    public static TPresenter Initialize<TPresenter, TView>() where TPresenter: BasePresenter<TView>, new()
    {
        return null;
    }
}

小补充,我来这里是因为我试图写一个扩展方法;

        public static T AutoJoinGroup<T, TD>(this T<TD> groupHubClientBase, string groupName)
            where T : GroupHubClientBase<TD>
        {
...
        }

你可以看到,我试图使用T<TD>,这是不正确的,你可以使用T

最新更新