gpt4 book ai didi

c# - 通用接口(interface)的非通用实现

转载 作者:行者123 更新时间:2023-11-30 20:24:22 25 4
gpt4 key购买 nike

我有以下一组 3 个接口(interface)和这些接口(interface)的 3 个实现。接口(interface)是用泛型定义的,最顶层的接口(interface)需要它的参数向下扩展第二个接口(interface);与第三个接口(interface)的第二个接口(interface)相同。这些类没有通用参数,而是使用特定类实现接口(interface),每个类都满足接口(interface)的要求。

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>)。

我将如何更正上述代码以解决该错误?

最佳答案

仅仅因为ExampleEntry可以隐式转换为 IEntry并不意味着 IRow<ExampleEntry>可以转换为 IRow<IEntry> .如果IRow就其通用参数而言是协变的,那么是的,这是可能的,但它不是现在的样子,因此隐式转换是不可能的。

如果你可以隐式转换 IRow<ExampleEntry>IRow<IEntry>那么你可以设置 Entries IEntry 数组的属性不是 ExampleRow 的类型.

关于c# - 通用接口(interface)的非通用实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26997923/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com