What a wonderful site I have been hiding here, reading other questions for ages, but now I have one of mine.
My workmate wrote a class very similar to the one below. As soon as I saw this, I knew that this would not work, but I have no explanation why it does not work.
What he expected when declaring it as ControlItem<Button>is that the Draw (Button) method will be called when using the base to call Draw (). Instead, we always throw an exception.
Is this a problem of covariance?
public abstract class ControlItem
{
public ControlItem()
{
}
abstract public void Draw();
}
public class ControlItem<T> : ControlItem where T : Control, new()
{
public T MyControl { get; set; }
private ControlItem()
{ }
public ControlItem(T control)
: base()
{
MyControl = control;
}
public override void Draw()
{
Draw(this.MyControl);
}
public void Draw(Control cntrl)
{
throw new NotImplementedException();
}
public void Draw(Button button)
{
}
}
Scott
source
share