简体   繁体   中英

How to solve generics error CS0311?

I have searched the web and stackoverflow and found many posts that deals with CS0311 error. None of the scenarios are close to mine. I have a generic class that inherits from a generic class.

Please note that BusinessBase is a class in the CSLA framework

What am I missing ?

public interface Itest
{
    int Digit();
}

class BB : Itest
{
    public int Digit()
    {
        return 20;
    }
}


class Test<T> : BusinessBase<T>, Itest where T : Test<T>, Itest
{
    public int Digit()
    {
        return 30;
    }
}

Test<Itest> test = new Test<Itest>(); //error CS0311

Error CS0311 The type 'MyTestApp.Itest' cannot be used as type parameter 'T' in the generic type or method 'A<T>' . There is no implicit reference conversion from 'MyTestApp.Itest' to 'MyTestApp.A<MyTestApp.Itest>' . MyTestApp

I agree with the compiler. T in your scenario is Itest . Your where condition demands that T : Test<T> (which immediately sounds suspect), which would require that ITest : Test<ITest> ... but ITest clearly doesn't (and can't) : Test<ITest> .

It is very very unclear what you intended to do, but I suspect you mean:

class Test<T> where T : Itest

and:

Test<BB> test = new Test<BB>();

You can go something like this:

interface Itest {}

class BusinessBase<T> {

}

class Test<T> : BusinessBase<T>, Itest where T : Test<T>, Itest {
    public int Digit() {
        return 30;
    }
}

class IT : Test<IT>, Itest {

}

class Program {
    public static int Main() {

        var t = new Test<IT>();
        t.Digit();
        return 0;
    }
}

Which to me is a really awful use of generics, but that is how CSLA works....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM