Reputation: 65
I'm having trouble getting my test to work with Generics and Polymorphism.
Here is the errors I am getting when I try to compile:
The type 'Testing.ChildBar' cannot be used as type parameter 'T' in the generic type or method 'Testing.BaseFoo'. There is no implicit reference conversion from 'Testing.ChildBar' to 'Testing.IBar'.
The type 'Testing.ChildBar' cannot be used as type parameter 'T' in the generic type or method 'Testing.BaseFoo'. There is no implicit reference conversion from 'Testing.ChildBar' to 'Testing.IFoo'.
And here is the code for a Console App that I'm getting the above error on:
class Program
{
static void Main(string[] args)
{
Console.ReadKey();
}
}
public interface IFoo
{
Task<bool> Method1();
Task<bool> Method2();
Task<bool> Method3();
Task<bool> Method4();
Task<bool> Method5();
}
public interface IBar<T> where T : BaseBar
{
T MyStuff { get; set; }
}
public abstract class BaseFoo<T> where T : BaseBar, IFoo, IBar<T>
{
public abstract T MyStuff { get; set; }
public abstract Task<bool> Method1();
public abstract Task<bool> Method2();
public abstract Task<bool> Method3();
public abstract Task<bool> Method4();
public abstract Task<bool> Method5();
}
public abstract class BaseBar
{
}
public class ChildBar : BaseBar
{
public string TestMethod { get { return "Testing123"; } }
}
public class ChildFoo : BaseFoo<ChildBar>
{
private ChildBar _myStuff;
public override ChildBar MyStuff
{
get
{
if (_myStuff == null)
{
_myStuff = new ChildBar();
}
return _myStuff;
}
set
{
_myStuff = value;
}
}
public override Task<bool> Method1() { return new Task<bool>(); }
public override Task<bool> Method2() { return new Task<bool>(); }
public override Task<bool> Method3() { return new Task<bool>(); }
public override Task<bool> Method4() { return new Task<bool>(); }
public override Task<bool> Method5() { return new Task<bool>(); }
private void Test()
{
var test = MyStuff.TestMethod;
}
}
What I would like to be able to do is create many different ChildFoo's that each have a "MyStuff" property, but that "MyStuff" property can be any class I create that inherits from BaseBar.
If you can think of a better way to do this. I'm all ears.
Upvotes: 2
Views: 119
Reputation: 156524
What I would like to be able to do is create many different ChildFoo's that each have a "MyStuff" property, but that "MyStuff" property can be any class I create that inherits from BaseBar.
I think that translates to this:
public abstract class BaseFoo<T> : IBar<T>, IFoo
where T : BaseBar
Since IBar<T>
defines the MyStuff
property, if you want children of BaseFoo
to have that property, you should be saying that BaseFoo
extends IBar<T>
. Your original code was saying that its generic argument (ChildBar
) should have that property.
Upvotes: 3