c# - 由特定通用包含接口(interface)参数化的通用容器接口(interface)

标签 c# generics interface containers restriction

目标:

创建由实现另一个特定通用接口(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 的能力通用参数并制作IVersionManagerIVersion 上通用仅使用一个通用参数。

因此,要在 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/

相关文章:

c# - 旋转和打印正方形

c# - 如果在 "using"语句中使用try/catch,一次性资源会被释放吗?

c# - 使用正则表达式限制字符数

swift - swift 中的一等泛型函数?

java - 使用接口(interface)而不是类来定义泛型

c# - 在 C# 的接口(interface)实现中使用继承的接口(interface)

c# - 如何使用来自外部应用程序的 View

generics - 如何在Kotlin中将通用类型的实例添加到列表中

forms - 不支持泛型的嵌套对象 : workarounds

java - 实例化具有默认方法的接口(interface)