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
.
精彩评论