I have an abstract class with a few inheriting classes like so:
internal abstract class SomeBaseType {}
internal class FirstSpecificType : SomeBaseType {}
internal class SecondSpecificType : SomeBaseType {}
internal class ThirdSpecificType : SomeBaseType {}
and a class with a constrained generic type parameter:
internal class SomeCollection<T> : ICollection<SomeDataStructure>
where T : SomeBaseType {}
I created a List<SomeCollection<SomeBaseType>>
and tried to add elements of various inheriting classes of SomeBaseType
but I get the following errors ( CS1503 and CS1950 ):
Argument 1: cannot convert from 'Namespace.SomeCollection<FirstSpecificType>' to 'Namespace.SomeCollection<SomeBaseType>'
The best overloaded Add method 'List<SomeCollection<SomeBaseType>>.Add(SomeCollection<SomeBaseType>)' for the collection initializer has some invalid arguments
Since FirstSpecificType
is a SomeBaseType
, I should be able to do this, right? It's basically the same as adding some arbitrary set of object
to an IList<object>
.
For additional context, the code where this error manifests looks like this:
protected Constructor()
{
collectionOne = new SomeCollection<FirstSpecificType>();
collectionTwo = new SomeCollection<SecondSpecificType>();
collectionThree = new SomeCollection<ThirdSpecificType>();
allCollections = new List<SomeCollection<SomeBaseType>>
{
// Each of these three collections has the error
collectionOne,
collectionTwo,
collectionThree
};
}
This is an issue of covariance and contravariance , that basically says that while FirstSpecificType
is indeed SomeBaseType
, SomeCollection<FirstSpecificType>
is strictly not SomeCollection<SomeBaseType>
.
Eric Lippert wrote some fabulous articles about this and giraffes that I'd recommend everybody to read at least once :-)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.