【发布时间】:2015-06-18 01:41:57
【问题描述】:
对于每个 *Collection(HtmlNodeCollection、TreeNodeCollection、CookieCollection 等)类实例,我需要传递给只接受数组或列表的方法(不应该有接受 @例如,TreeView 中的 987654326@?)我必须编写这样的扩展方法:
public static TreeNode[] ToArray(this TreeNodeCollection nodes)
{
TreeNode[] arr = new TreeNode[nodes.Count];
nodes.CopyTo(arr, 0);
return arr;
}
或遍历整个集合,将项目添加到输出列表,然后将输出列表转换为数组:
public static TreeNode[] ToArray(this TreeNodeCollection nodes)
{
var output = new List<TreeNode>();
foreach (TreeNode node in nodes)
output.Nodes(node);
return output.ToArray();
}
所以,我的问题是:
我经常需要这种扩展方法。如果列表很大,它可能会分配大量内存,就像通常一样。为什么我不能只获取此*Collection 类使用的内部数组的引用(而不是复制),这样我就无需使用该扩展并执行此内存分配?甚至提供ToArray() 方法。我们不需要知道它的内部实现或在最后一种情况下使用的数组。
【问题讨论】:
-
I need to pass to a method which accepts only an array or list为什么不IEnumerable<T>?您可以轻松传递treeNodeCollection.Cast<TreeNode>()为ex。 -
使用
IEnumerable<T>。如果您需要数组,请使用collection.Cast<TreeNode>().ToArray()并完全摆脱您的扩展方法。 -
.Cast<>()真的很好...collection.Cast<TreeNode>().ToArray()与我的.ToArray()扩展名有什么不同(当然,除了它是本地的)?
标签: c# arrays collections