type参数不能与类型参数一起使用

时间:2011-08-31 23:04:47

标签: c# .net generics

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

它抛出了我的例外:

  

type参数不能与类型参数一起使用

代码:

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

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

我看了几篇没有明确解释的帖子为什么我无法说T1<T2>

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

5 个答案:

答案 0 :(得分:12)

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

通过引用参数使其工作并不清楚你的意思 - 你用于该ref参数的任何类型都应该可以作为返回类型。我的猜测是它只是TPresenter类型,而不是TPresenter<TView>

答案 1 :(得分:1)

没有TPresenter<TView>这样的东西没有意义。 TPresenter只是一个占位符,直到它受到任何东西的限制,例如:没有int<tview>所以你不能拥有它。添加约束后,它意味着它必须是BasePresenter<TView>或某种派生类型,因此它始终为Something<TView>,因此再次TPresenter<TView>毫无意义。

答案 2 :(得分:0)

这是一个旧的,但我也打了它。在类定义中,只使用单一类型,然后使用多种类型。 E.g:

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>>();
}

答案 3 :(得分:0)

我的代码中出现了类似的错误。 @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;
    }
}

答案 4 :(得分:0)

另外,我来这里是因为我试图编写扩展方法;

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

如您所见,我尝试使用不正确的T<TD>,您可以只使用T