Multiple Limit Priorities for a Generic Type Parameter

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 { //some foobar stuffs } class Foobar : FoobarBase, IFoobar<Foobar> { public Foobar CreateFoobar() { return new Foobar(); } } class FoobarList<T> where T : FoobarBase, IFoobar<T> { void Test(T rFoobar) { T foobar = rFoobar.CreateFoobar(); } } 

It is cumbersome to divide Foobar into two classes. Is there a better way to fix this?

+6
source share
1 answer

Just press rFoobar on IFoobar<T> :

 T foobar = ((IFoobar<T>)rFoobar).CreateFoobar(); 

So you call a method that returns T , not just Foobar .

As Rother says, changing the method in Foobar to use an explicit implementation of the interface, too:

 Foobar IFoobar<Foobar>.CreateFoobar() { return new Foobar(); } 

Thus, this method will not be found in T , so it will again be allowed for the interface method.

+4
source

All Articles