【问题标题】:How to create a list that contains a list of different types如何创建包含不同类型列表的列表
【发布时间】:2017-10-08 23:16:46
【问题描述】:

假设我有这样的列表:

var firstList = new List<ofsometype>();
var secondList = new List<ofsomeanothertype>();
var thirdList = new List<anothertype>();

如何制作一个接受这些列表的列表?喜欢

var mainList = new List<???>();
mainList.Add(firstlist);
mainList.Add(secondlist);
mainList.Add(thirdlist);

谢谢。

【问题讨论】:

  • 使用List&lt;object&gt; - 但是你会进入cast-o-rama的领域......
  • 好吧,除非他们实现了一些通用的东西,否则你只能使用List&lt;object&gt;。 List&lt;T&gt; 也实现了一些非通用接口,但不知道您打算将列表用于什么以及打算如何使用它,因此无法给您更具体的建议。
  • @LasseV.Karlsen 实际上我正在生成许多类型的列表,然后我将加入它们。就是这样。
  • 你也可以试试var mainList = new List&lt;IList&gt;();
  • 如果类型是您的,您可以为它们添加一个不错的接口,最好的接口提供有用的服务,beyobf 是可列出的..

标签: c#


【解决方案1】:

如果你想从不同类型的列表中添加项目,那么它们需要共享一个公共基类,或者从同一个接口继承,例如

ofsometype : ISomeInterface
ofsomeanothertype: ISomeInterface
anothertype: ISomeInterface

var firstList = new List<ofsometype>();
var secondList = new List<ofsomeanothertype>();
var secondList = new List<anothertype>();

var mainList = new List<ISomeInterface>();
mainList.AddRange(firstlist);
mainList.AddRange(secondlist);
mainList.AddRange(thirdlist);

在从列表中检索项目时,您将被限制访问由 ISomeInterface 公开的成员,除非您使用强制转换/反射。

这也可以通过将它们添加到List&lt;object&gt; 来实现,但这几乎不会为您提供有关列表中包含的内容的信息。

【讨论】:

  • 感谢您的回答。如果我使用List&lt;object&gt;,我是否能够迭代主列表并获取成员(不同类型的列表)。
  • @jason 您是否考虑过使用字典的选项,其中键是类型,值是 IList 对象?在检索列表时,它会使转换变得更容易一些——尽管它只有在最多有一个具有某种类型的列表时才会起作用。
【解决方案2】:

我可能会改用 Dictionary 集合:

var firstList = new List<ofsometype>();
var secondList = new List<ofsomeanothertype>();
var thirdlist = new List<anothertype>();

var listsDict = new Dictionary<Type, object>();
listsDict.Add(typeof(ofsometype), firstlist);
listsDict.Add(typeof(ofsomeanothertype), secondlist);
listsDict.Add(typeof(anothertype), thirdlist);

这里的优点是它可以为您提供有关列表类型的信息。这可以用于两件事:

  1. 仅针对特定类型的过滤器列表
  2. 稍后只需使用密钥即可知道List&lt;object&gt; 的类型

附言

根据解决方案是什么以及您需要实现什么,您可以使用泛型(如果类型已知)或dynamics - 如果类型未知,但仍然需要在运行时进行动态操作,如果编译器不知道类型。

【讨论】:

  • 我更喜欢这个答案而不是 IList 一个列表,它读起来更清晰,并防止了其他解决方案的许多铸造问题
  • 你能举一个转换的例子吗?
  • @Dillanm 为什么这可以防止投射问题?您仍然必须转换列表,在使用对象列表的情况下,您必须转换对象。我不明白为什么这是更好的解决方案。
  • @Maarten 抱歉,它可能不会阻止每个 sé 的转换问题,但它至少可以帮助您告诉您根据字典的键将对象转换为什么,列表方法没有这个优势。
  • @Dillanm tbh 这可以使用反射来完成,但它可能会影响性能,并且使用 Key 更容易。
【解决方案3】:

只需使用对象。

List&lt;Object&gt; 或 Object[] 用于数组

var mainList = new List<List<Object>>();
mainList.Add(firstlist);
mainList.Add(secondlist);
mainList.Add(thirdlist);

我建议这个

var mainList = new List<Object[]>();
mainList.Add(firstlist.toArray());
mainList.Add(secondlist.toArray());
mainList.Add(thirdlist.toArray());

【讨论】:

    猜你喜欢
    • 2020-01-01
    • 2013-10-13
    • 2011-11-21
    • 2021-12-25
    • 2017-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多