[英]C# List of inherited classes
I have the following classes: 我有以下课程:
public class BaseClass() {}
public class Class1 : BaseClass {}
public class Class2 : BaseClass {}
public class BaseClassList : List<BaseClass> {}
public class Class1List : List<Class1> {}
public class Class2List : List<Class2> {}
The data is in JSON format are is loaded as a list of BaseClass objects. JSON格式的数据将作为BaseClass对象的列表加载。 Once loaded and want to populate the specific lists with the relevant objects: 加载后,要使用相关对象填充特定列表:
public void Setup()
{
Class1List list1 = new Class1List();
var query = from x in BaseClassList
where x.Type = MyType.Class1
select x;
list1.AddRange(query);
}
However AddRange doesn't compile because I'm trying to added BaseClass objects to a Class1 list. 但是,AddRange无法编译,因为我试图将BaseClass对象添加到Class1列表中。
How can I successfully add the inherited classes? 如何成功添加继承的类?
Try this code snippet, 试试这个代码片段,
public void Setup()
{
Class1List list1 = new Class1List();
var query = from x in BaseClassList
where x.GetType() == typeof(Class1)
select x as Class1;
list1.AddRange(query);
}
The as operator casts your type BaseClass
to type Class1
as运算符将类型BaseClass
强制转换为Class1
类型
Reference: MSDN as Operator 参考: MSDN作为运营商
As mentioned in a comment, you can do it a little bit more save with this snippet: 如评论中所述,您可以通过以下代码片段来节省更多时间:
public void Setup()
{
Class1List list1 = new Class1List();
var query = from x in BaseClassList
where x.GetType() == typeof(Class1)
select x;
foreach(var item in query){
var temp = item as Class1;
if(temp != null)
list1.Add(temp);
}
}
After casting to Class1 you can check for null, as the as
operator returns null if unable to cast. 强制转换为Class1后,您可以检查是否为null,因为as
运算符如果无法强制转换,则返回null。 I would prefer to make a type compare with where x.GetType() == typeof(Class1)
我希望将类型与where x.GetType() == typeof(Class1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.