Dav*_*ide 9 c# generics interface
我有一个接口模式,如下所示(C#.NET4)
interface A
{
}
interface B
{
List<A> a;
}
interface C
{
List<B> b;
}
Run Code Online (Sandbox Code Playgroud)
我以这种方式实现它:
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
}
Run Code Online (Sandbox Code Playgroud)
我不知道如何避免错误使用泛型类型'B'需要1个类型的参数
Jon*_*Jon 10
由于interface B<T>是通用的,因此在声明时需要为它提供正式的类型参数interface C<T>.换句话说,当前的问题是你没有告诉编译器B接口C"继承"了什么类型的接口.
两者T不一定是指同一类型.它们可以是相同的类型,如
public interface C<T> where T : B<T>, A { ... }
Run Code Online (Sandbox Code Playgroud)
或者它们可以是两种不同的类型:
public interface C<T, U> where T : B<U> where U : A { ... }
Run Code Online (Sandbox Code Playgroud)
在第一种情况下,对类型参数的限制当然更严格.