I get an error when trying to add a shared object to the list <>.
This is probably due to covariance and contravariance, but I'm not sure how to get around this. I tried to restrict my generic types using T: IRegister.
I have an interface to represent a register, and then two classes that are ByteRegister and DoubleWordRegister.
public interface IRegister { string Name {get;set;} } public class ByteRegister : IRegister { ... } public class DoubleWordRegister : IRegister { ... }
Then I have another class that represents a block of these registers 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 that is used to define a list of register blocks and each register in a 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 get the following error:
Error 20 Argument '1': cannot convert from 'RegisterBlock<ByteRegister>' to 'RegisterBlock<IRegister>'
in the line _blocks.Add (block1) and similarly on _blocks.Add (block2);
source share