【发布时间】:2014-11-18 15:29:12
【问题描述】:
我有以下 3 个接口和这些接口的 3 个实现。接口是用泛型定义的,最顶层的接口需要其参数向下扩展第二个;与第三个接口的第二个接口相同。这些类没有泛型参数,而是通过特定的类实现接口,每个类都满足接口的要求。
namespace GenericsIssueExample
{
interface IGroup<Row> where Row : IRow<IEntry>
{
Row[] Rows {
get;
set;
}
}
interface IRow<Entry> where Entry : IEntry
{
Entry[] Entries {
get;
set;
}
}
interface IEntry
{
int Value {
get;
set;
}
}
class ExampleGroup : IGroup<ExampleRow>
{
private ExampleRow[] rows;
public ExampleRow[] Rows {
get { return rows; }
set { rows = value; }
}
}
class ExampleRow : IRow<ExampleEntry>
{
private ExampleEntry[] entries;
public ExampleEntry[] Entries {
get { return entries; }
set { entries = value; }
}
}
class ExampleEntry : IEntry
{
private int val = 0;
public int Value {
get { return val; }
set { val = value; }
}
}
}
当我尝试编译上面的代码时,我得到以下编译错误:
The type 'GenericsIssueExample.ExampleRow' cannot be used as type parameter 'Row' in the generic type or method 'GenericsIssueExample.IGroup<Row>'. There is no implicit reference conversion from 'GenericsIssueExample.ExampleRow' to 'GenericsIssueExample.IRow<GenericsIssueExample.IEntry>'.
这个错误在第27行,也就是ExampleGroup的定义:
class ExampleGroup : IGroup<ExampleRow>
我不明白为什么会发生这种情况,因为 ExampleRow 确实实现了 IRow<IEntry>。 (IRow<ExampleEntry>)。
如何更正上述代码以解决该错误?
【问题讨论】:
-
您已将所有泛型参数声明为不变量(没有
in或out修饰符),因此该问题似乎是有效的。如果您的界面中只需要gets,则添加适当的修饰符后可能会起作用。 -
搜索词“协方差”...即stackoverflow.com/questions/16317541/… - 可能的最短摘要 -
class A:B并不意味着IX<A>:IX<B>。 -
@GáborBakos 我确实需要同时拥有
gets 和sets,但我想我找到了另一个解决方案。将IGroup更改为interface IGroup<Row, Entry> where Row : IRow<Entry> where Entry : IEntry和ExampleGroup更改为class ExampleGroup : IGroup<ExampleRow, ExampleEntry>是最好的解决方案吗?