【发布时间】:2017-08-24 09:50:39
【问题描述】:
我有问题。 例如,考虑这 4 个类。
public abstract ParentContainer<T> where T: Parentfoo
{
public List<T> fooList;
}
//Let there be many different ChildContainers with different types.
public class ChildContainer : ParentContainer<ChildFoo>
{
}
public abstract class ParentFoo
{
public string name;
}
public class ChildFoo : ParentFoo
{
}
我如何编写一个接受任意 ChildContainer 列表作为参数的方法, 哪些对他们的 fooLists 进行操作? 有没有可能?
补充说明,ParentContainer有很多不同的children, 每个都有一个 foo 的不同子项的列表。
public class ChildContainerB : ParentContainer<ChildFooB>{}
public class ChildContainerC : ParentCOntainer<ChildFooC>{}
...
public class ChildFooB : ParentFoo;
public class ChildFooC : ParentFoo;
那我需要一个类似这样的方法
//X means it can be any arbitrary ChildContainer
public void method(List<ChilContainerX> list)
{
foreach(ChildContainerX x in list)
{
print(x.fooList.Last().name);
}
}
【问题讨论】:
-
所有
ChildContainer实例都会有一个ChildFoo列表,所以是的,这是可能的,但我怀疑这不是你想要的。你能解释一下吗? -
您至少可以编译您发布的示例代码吗?什么是
foo,你的意思是ParentFoo? -
另外,当你说任意ChildContainers的列表时,你真的是说任何继承自ParentContainer的对象的列表
? -
@DavidG 是的,我就是这个意思。
-
@GiulioCaccin 是的,对不起。我已经更正了我的示例代码!感谢您的提示!
标签: c# list class generics methods