简体   繁体   中英

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)

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...

构造List<MyType>可以将List<MyType>作为参数MyTypes ,然后将其传递给基类构造函数。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM