The other answers are correct but it is instructive to reason out why the compiler flags this as unsafe. Suppose we allowed it; what could go wrong?
class Sprocket: Product {}
class Gadget : Product {}
class GadgetFactory : IFactory<Gadget>
{
public List<Gadget> MakeStuff()
{
return new List<Gadget>() { new Gadget(); }
}
}
... later ...
IFactory<Gadget> gf = new GadgetFactory();
IFactory<Product> pf = gf; // Covariant!
List<Product> pl = pf.MakeStuff(); // Actually a list of gadgets
pl.Add(new Sprocket());
and hey, we just added a sprocket to a list that can only contain gadgets.
There is only one place where the compiler can detect the problem, and that's in the declaration of the interface.
Sorry about the somewhat excessively jargonish error message. I couldn't come up with anything better.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…