c# - 如何使用子泛型接口(interface)实现泛型接口(interface)

标签 c# c#-4.0 generics interface

当父/子接口(interface)都是通用的时,我在实现父/子接口(interface)时遇到了问题。我能找到的最佳答案是不可能,但我也找不到其他人问完全相同的问题。我希望我只是不知道让编译器理解我正在尝试做的事情的正确语法。这是我尝试实现的代码的精简示例。

public interface I_Group<T>
    where T : I_Segment<I_Complex>
{
    T Segment { get; set; }
}

public interface I_Segment<T>
    where T : I_Complex
{
    T Complex { get; set; }
}

public interface I_Complex
{
    string SomeString { get; set; }
}

public partial class Group : I_Group<Segment>
{   
    private Segment segmentField;

    public Group() {
        this.segmentField = new Segment();
    }

    public Segment Segment {
        get {
            return this.segmentField;
        }
        set {
            this.segmentField = value;
        }
    }
}

public partial class Segment : I_Segment<Complex> {

    private Complex complexField;

    public Segment() {
        this.complexField = new Complex();
    }

    public Complex Complex {
        get {
            return this.c_C001Field;
        }
        set {
            this.c_C001Field = value;
        }
    }
}

public partial class Complex : I_Complex {

    private string someStringField;

    public string SomeString {
        get {
            return this.someStringField;
        }
        set {
            this.someStringField = value;
        }
    }
}

所以在这里,Complex 是孙子,它实现了 I_Complex 而没有错误。 Segment 是它的父级,它实现 I_Segment 没有错误。问题出在尝试实现 I_Group 的祖 parent 组。我得到错误

The type 'Segment' cannot be used as type parameter 'T' in the generic type or method 'I_Group<T>'. There is no implicit reference conversion from 'Segment' to 'I_Segment<I_Complex>'.

我被引导相信这是协变性的问题,但我也被引导相信这是应该在 C# 4.0 中工作的东西。这在 child 不是通用的时候有效,这让我认为必须存在一些语法才能正确编译。难道我做错了什么?这可能吗?如果不是,有人可以帮助我理解为什么不是吗?

最佳答案

您可以将第二个泛型类型参数添加到 I_Group 接口(interface)声明中:

public interface I_Group<T, S>
    where T : I_Segment<S>
    where S : I_Complex
{
    T Segment { get; set; }
}

并在 Group 类声明中明确指定这两种类型:

public partial class Group : I_Group<Segment, Complex>

它会让你的代码通过编译。

关于c# - 如何使用子泛型接口(interface)实现泛型接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18937645/

相关文章:

c# - 如何使在 Azure 实例中运行的 ASP.NET WebAPI 程序每分钟更新一次数据库?

c# - 防止机器名称附加到端点名称

c# 无法处理没有有效操作参数的请求。请提供有效的 SOAP 操作

c#-4.0 - 如何获取字符串的宽度

java - 泛型混淆 : deceiving the compiler

c# - ElasticSearch 查询检索书籍的所有标签

c# - protected 通用类 - 是否受支持?

asp.net-mvc-3 - 具有无参数构造函数的 Ninject 和 Provider 模型

java - 检查异常差异

java - 如何在静态泛型工厂方法中避免 "Type mismatch"?