C#继承带有约束的泛型类

时间:2017-02-26 13:00:48

标签: c# generics inheritance generic-constraints

所以,我有一个界面:

interface A<SomeType>
{
    SomeType Abc(SomeType);
    .....
}

我有一个班级:

class B<ShouldBeClassA<AnyType>> 
     where ShouldBeClassA<AnyType> : A<AnyType>
{ ShouldBeClassA<AnyType> someVariable; .....}

但是这会导致语法错误,我想要的是强制someVariable成为

的衍生物
A<AnyType>

所以我可以这样做:

class B......
{
    ....
    void Method()
    {
        someVariable.Abc(anyTypeVariable);
    }
 ......}

你能告诉我,如何解决这个问题?

以下是实际代码:

public interface IGenericTeacher<Genome<GenomeType>>
    where Genome<GenomeType> : IGenome<GenomeType>
{

    /// <summary>
    /// Pass the tests and save the results.
    /// </summary>
    void PassTests();

    /// <summary>
    /// Passing generation, according to the results.
    /// </summary>
    void PassGeneration();

}


public interface IGenome<GenomeType>
{
   .......

1 个答案:

答案 0 :(得分:1)

您的界面应该是:

public interface IGenericTeacher<T> where T : IGenome<T>
{
    //...
}