I'm getting an error when trying to add generic object to a List<>.
Its probably related to Covariance and Contravariance but I not sure how to work around this. I've tried to restrict my generic types using where T: IRegister.
I have an interface to represent a register and then two classes which represent a ByteRegister and a DoubleWordRegister.
public interface IRegister
{
string Name {get;set;}
}
public class ByteRegister : IRegister
{
...
}
public class DoubleWordRegister : IRegister
{
...
}
I then have another class which represents a block of these registers all of the same type.
public class RegisterBlock<T> where T:IRegister
{
private IList<T> _registers;
... constructors, properties etc
public void AddRegister(T register)
{
_registers.Add(register);
}
}
And finally I have a RegisterMap class which is used to define the list of register blocks and each register within the block.
public class RegisterMap
{
private List<RegisterBlock<IRegister>> _blocks;
public RegisterMap()
{
_blocks = new List<RegisterBlock<IRegister>>();
RegisterBlock<ByteRegister> block1= new RegisterBlock<ByteRegister>("Block1", 0);
block1.AddRegister(new ByteRegister("Reg1"));
block1.AddRegister(new ByteRegister("Reg2"));
_blocks.Add(block1);
RegisterBlock<DoubleWordRegister> block2= new RegisterBlock<DoubleWordRegister>("Block2", 10);
block2.AddRegister(new DoubleWordRegister("Reg3"));
block2.AddRegister(new DoubleWordRegister("Reg4"));
block2.AddRegister(new DoubleWordRegister("Reg5"));
_blocks.Add(block2);
}
}
However I'm getting the following error:
Error 20 Argument '1': cannot convert from 'RegisterBlock<ByteRegister>' to 'RegisterBlock<IRegister>'
on the line _blocks.Add(block1) and similarly on _blocks.Add(block2);
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…