嵌套的通用接口 [英] Nested generic interfaces
问题描述
我有一个类似于以下(C#.NET4)的接口架构
I have a schema of interfaces like the following (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个类型参数
I don't know how to avoid the error Using the generic type 'B' requires 1 type arguments
推荐答案
由于interface B<T>
是通用的,因此在声明interface C<T>
时需要为其提供一个形式类型参数.换句话说,当前的问题是您没有告诉编译器继承"接口B的类型是什么.
Since interface B<T>
is generic, you need to provide a formal type argument for it when declaring interface C<T>
. In other words, the current problem is that you are not telling the compiler what type of interface B interface C "inherits" from.
两个T
不一定引用相同的类型.它们可以是与
The two T
s will not necessarily refer to the same type. They can be the same type, as in
public interface C<T> where T : B<T>, A { ... }
或者它们可以是两种不同的类型:
or they can be two distinct types:
public interface C<T, U> where T : B<U> where U : A { ... }
在第一种情况下,对类型参数的限制当然会更严格.
The restrictions on the type argument are of course tighter in the first case.
这篇关于嵌套的通用接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!