嵌套泛型接口

12

我有一个接口模式如下(C# .NET4)

interface A 
{

}

interface B 
{
    List<A> a;
}

interface C 
{
    List<B> b;
}

我是这样实现的:

public interface A 
{

}

public interface B<T> where T : A 
{
    List<T> a { get; set; }
}

public interface C<T> where T : B
{
    List<T> b { get; set; } // << ERROR: Using the generic type 'B<T>' requires 1 type arguments
}

我不知道如何避免出现错误“使用泛型类型'B'需要1个类型参数”


1
你没有实现任何接口... - Maarten
我用了错误的动词 :) .. 基本上所有的答案都很好,谢谢大家。 - Davide
5个回答

10

由于 interface B<T> 是泛型的,所以在声明 interface C<T> 时需要为其提供一个正式类型参数。换句话说,当前的问题是您没有告诉编译器接口 C “继承”自哪种类型的接口 B。

这两个 T 不一定指代相同的类型。它们可以是相同的类型,例如:

public interface C<T> where T : B<T>, A { ... }

或者它们可以是两种不同的类型:
public interface C<T, U> where T : B<U> where U : A { ... }

当然,在第一种情况下,类型参数的限制更加严格。


1

C 看起来像是通用的通用类型(说不出更好的词)。

这个 C 的定义能否代替呢?

public interface C<T,U> where T : B<U> where U : A
{
    List<T> b{ get; set; } 
}

1

由于接口 B 中的泛型类型只能是类型 A 的实例,因此在接口 C 中,您需要声明类型 T 为类型 B<A>

public interface A { }
public interface B<T> where T : A
{
    List<T> a { get; set; }
}
public interface C<T> where T : B<A>
{
    List<T> b { get; set; } 
}

1
这是因为您有一个<List<T>>,其中TB<T>,目前它被视为List<B>,您需要为B指定类型。这就是您出错的原因。
public interface C<T, T2> where T : B<T2>
  where T2 : A
{
  List<T> b { get; set; } 
}

将类型为 T2 的变量转换为类型 A,然后就没问题了 :)

1

你可以在这里添加一个额外的界面,例如:

public interface A { }
public interface B<T> where T : A
{
    List<T> a { get; set; }
}
public interface BA : B<A>
{ 
}
public interface C<T> where T : BA
{
    List<T> b { get; set; } // << ERROR: Using the generic type 'B<T>' requires 1 type arguments
}

它解决了目的吗?


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接