开发者

C#: Casting a partial class to a parent class and putting it into a Dictionary

Say I have the following classes:

public class Parent
{
   public Property1 {get;set;}
   public Property2 {get;set;}
}

public partial class Child : Parent { }

public partial class Cousin : Parent { }

I've got methods that return IQueryable<Child> and IQueryable<Cousin> using Property1 and Property2.

Is it possible to add both as lists into a Dictionary<string, List<Parent>>?

I've tried:

var childList = db.GetChildList() as List<Parent>;

But this returns null.

Would i have to return List<Child> and add them into a List before adding it to开发者_运维知识库 the dictionary?

Thanks


Since lists are invariant, it would need to be a right-typed list, for example:

var childList = db.GetChildList().Cast<Parent>().ToList();


Yes to your question. The reason is List<Child> is not derived from List<Parent>, only Child is derived from Parent.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜