从两个层次结构接口继承

本文关键字:层次结构 接口 继承 两个 | 更新日期: 2024-10-23 00:09:18

我有两个接口,其中一个具有泛型类型。但当我尝试使用它们时,我做不到。

第一个接口是:

interface IGene
{
    string Name { get; set; }
    int Index { get; set; }
}

第二种是:

interface IChromosome<X> where X :IGene
{
    double Fitness { get; }
    X[] Genes { get; set; }
}

实现这些的类:

class GAMachine<T> where T : IChromosome<X> where X:IGene
{
   //......
}

在最后一段代码中,它给出了一个错误。如何编写此层次顺序?有其他选择吗?

从两个层次结构接口继承

这是因为您没有在泛型类型定义中的类定义中定义X。我想你想要的是这个。

class GAMachine<T> where T : IChromosome<IGene>
{
   //....
}

或者这个

class GAMachine<T, X> where T : IChromosome<X> where X : IGene
{
   //....
}