将此 ArrayList 转换为通用列表是否有效? [英] Is converting this ArrayList to a Generic List efficient?

查看:24
本文介绍了将此 ArrayList 转换为通用列表是否有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写的代码从非托管代码接收一个 ArrayList,这个 ArrayList 将始终包含一个或多个 Grid_Heading_Blk 类型的对象.我已经考虑将此 ArrayList 更改为通用列表,但我不确定转换操作是否会如此昂贵,以至于抵消了使用通用列表的好处.目前,我只是运行 foreach (Grid_Heading_Blk in myArrayList) 操作以在将 ArrayList 传递给将使用它的类后处理 ArrayList 内容.

The code I'm writing receives an ArrayList from unmanaged code, and this ArrayList will always contain one or more objects of type Grid_Heading_Blk. I've considered changing this ArrayList to a generic List, but I'm unsure if the conversion operation will be so expensive as to nullify the benefits of working with the generic list. Currently, I'm just running a foreach (Grid_Heading_Blk in myArrayList) operation to work with the ArrayList contents after passing the ArrayList to the class that will use it.

我应该将 ArrayList 转换为泛型类型列表吗?如果是这样,最有效的方法是什么?

Should I convert the ArrayList to a generic typed list? And if so, what is the most efficient way of doing so?

推荐答案

这里尝试了一种从 ArrayList 创建通用列表的高性能方法.

Here's a stab at a performant way to create a generic list from an ArrayList.

List<Grid_Heading_Blk> myList = new List<Grid_Heading_Blk>(source.Count);
myList.AddRange(source.OfType<Grid_Heading_Blk>());

通过调用接受 int 的构造函数,后备存储只分配一次.

By calling the constructor that accepts an int, the backing storage is allocated only once.

与往常一样,您应该使用您通常使用的任何工具来衡量性能.

As always, you should measure the performance using whatever tools you normally use.

这篇关于将此 ArrayList 转换为通用列表是否有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆