Cast List<MyType> to Class that extends List<MyType>
Here's the problem
I'm trying to cast form List to an object MyTypes 开发者_运维问答which is defined as
public class MyTypes : List<MyType> { ... }
It won't cast directly with (MyTypes) - compiler error
Or with as MyTypes - returns null
I would think this would be possible, but clearly I have to overload some casting operation.
Help!
If MyTypes inherits from List you cannot cast a List if MyType.
Example this is not valid:
MyTypes foo = new List<MyType>();
This is valid:
List<MyType> foo = new MyTypes();
MyTypes bas = (MyTypes) foo;
You cannot cast a base class isntance to an inherited type, example, you cannot cast from Vehicle to Car but you can do it from Car to Vehicle (If Car : Vehicle)
You could pass your List<MyType>
in as a parameter when constructing your MyTypes
and then hand this off to the base class constructor..
If I understand you correctly, you have a List<MyType>
, and you want to cast it to a MyTypes
, which derives from (inherits) from List<MyType>
...
You can't do this... If you had a MyTypes
you could cast it up the imnheritence chain to a List<MyType>
. But you can't cast down the inheritence chain...
精彩评论