目标:
创建由实现另一个特定通用接口(interface)的类型参数化的通用接口(interface)。
问题:
我正在尝试用 C# 编写以下相关接口(interface),但我无法确定我正在尝试做的事情是否可行。
public interface IVersion<T>
{
IVersionManager<IVersion<T>> Parent { get; }
// various other methods
}
public interface IVersionManager<T> where T : IVersion<T>
{
IReadOnlyList<T> Versions { get; }
T Current { get; }
void AddVersion(T version);
// various other methods
}
不幸的是,Visual Studio 似乎在 IVersionManager<IVersion<T>>
中找到了自引用 ( IVersion<T>
)界面相当令人反感。
它抛出以下错误:
The type '
IVersion<T>
' must be convertible to 'IVersion<IVersion<T>>
' in order to use it as a parameter 'T' in the generic interface 'IVersionManager<T>
'
这听起来好像是圆形的,但我认为它实际上不是。
这对我来说很有意义。我疯了吗?这可能吗?我只希望子版本能够引用它的父管理器。
Google 搜索没有找到任何结果。我怀疑也许我只是不知道如何表达这个问题。
最佳答案
我想它应该是:
public interface IVersion<T>
{
IVersionManager<T> Parent { get; }
// various other methods
}
public interface IVersionManager<T>
{
IReadOnlyList<IVersion<T>> Versions { get; }
IVersion<T> Current { get; }
void AddVersion(IVersion<T> version);
// various other methods
}
不需要定义 where
实现类型安全的约束。但缺点是你的VersionManagers
不是由实际定义的 Version<T>
类型但按类型 T
用于定义 Version<T>
.
我不知道有什么真正的方法可以同时实现定义 IVersion's
的能力通用参数并制作IVersionManager
在 IVersion
上通用仅使用一个通用参数。
因此,要在 IVersion
上实现真正的“通用性”实现者你将不得不使用更复杂的类型和限制:
public interface IVersion<T>
{
IVersionManager<T> Parent { get; }
// various other methods
}
public interface IVersionManager<TVersion, T>
where TVersion : IVersion<T>
{
IReadOnlyList<TVersion> Versions { get; }
TVersion Current { get; }
void AddVersion(TVersion version);
// various other methods
}
它有点多余和笨重,但允许创建更多指定的 VersionManagers
, 在 IVersion
上是真正通用的实现者。
关于c# - 由特定通用包含接口(interface)参数化的通用容器接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24539846/