ArrayList.ToArray(Type) Or ArrayList.CopyTo(Array)

≡放荡痞女 提交于 2020-02-27 02:45:27

转自:http://blogs.geekdojo.net/richardhsu/archive/2003/11/08/268.aspx

I was using ArrayList.CopyTo(Array) to convert arraylist to a type[] array.

I thought ArrayList.ToArray(Type) was for intrinsic types (int, string etc.) but forgot that one the facilitites of OOP is that types that we define can be treated as instinsic types for most occasions. Today I came across a code that showed the use of ArrayList.ToArray(Type) for a type defined by the programmer.

...
return (Contact[])mContacts.ToArray(typeof(Contact));
...

here mConstacts is of type ArrayList, and Contact is a class.

I was doing the following till now :-

C# :-

Contact[] contacts = new Contact[mContacts.Count];

mContacts.CopyTo(contacts);

return contacts;

I have yet to peek into the IL to see the difference/similarity between the two approaches in terms of internals, but the first one at least requires less code and fits in a single line. :-)

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!