In the following example, I have two limitations: Foobar and IFoobar<T> , type T in the generic class FoobarList<T> . But the compiler gives an error: cannot implicitly convert the type "Foobar" to "T". Explicit conversion exists (are you skipping listing?)
interface IFoobar<T> { T CreateFoobar(); } class Foobar : IFoobar<Foobar> { //some foobar stuffs public Foobar CreateFoobar() { return new Foobar(); } } class FoobarList<T> where T : Foobar, IFoobar<T> { void Test(T rFoobar) { T foobar = rFoobar.CreateFoobar(); //error: cannot convert Foobar to T } }
It seems that the compiler considers CreateFoobar as a method in Foobar, but not the one in IFoobar. I can fix the compilation by splitting Foobar into the base class FoobarBase and implementing the IFoobar interface in its derived class as follows:
interface IFoobar<T> { T CreateFoobar(); } abstract class FoobarBase {
It is cumbersome to divide Foobar into two classes. Is there a better way to fix this?
source share